简体   繁体   English

返回导航到最后一个片段

[英]Back Navigation to last Fragment

I have two Fragments in my ViewPager as Tabs. 我的ViewPager中有两个片段作为选项卡。 These share a toolbar. 这些共享工具栏。 You get to the SettingsActivity by clicking an Icon on the toolbar. 通过单击工具栏上的图标,可以进入SettingsActivity。 So you can access the SettingsActivity while either Fragment A is the visible one, or Fragment B is the visible one. 因此,您可以在“片段A”为可见片段或“片段B”为可见片段时访问SettingsActivity。 When I navigate back from the SettingsActivity to the fragments, by clicking the Up Button in the toolbar (actionBar.setDisplayHomeAsUpEnabled(true);), I want to have the fragment visible, that I had visible when I accessed SettingsActivity. 当我从SettingsActivity导航回到片段时,通过单击工具栏上的向上按钮(actionBar.setDisplayHomeAsUpEnabled(true);),我希望使片段可见,即访问SettingsActivity时可见的片段。 Without any special code (= current state) it seems to always return to the first Fragment in the ViewPager (ie the most left one). 没有任何特殊代码(=当前状态),它似乎总是返回到ViewPager中的第一个Fragment(即最左边的一个)。 Parent Activity for the Up Navigation is MainActivity, where I have the ViewPager with the 2 Fragments as Tabs. 向上导航的父活动是MainActivity,在这里,我将带有2个片段的ViewPager作为选项卡。

Use the state saving callback to save the state of your MainActivity: 使用状态保存回调来保存MainActivity的状态:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("SELETED_TAB_INDEX", mSelectedTabIndex);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(savedInstanceState != null) { // so the activity is being restarted
        pager.setCurrentItem(savedInstanceState.getInt("SELETED_TAB_INDEX"));
    }
}

save your fragment to backstack. 将您的片段保存到堆栈。 This way, back button for fragments would work same as it runs for activities. 这样,片段的后退按钮将与活动运行的按钮相同。

Here: http://developer.android.com/training/implementing-navigation/temporal.html 此处: http//developer.android.com/training/implementing-navigation/temporal.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM