简体   繁体   中英

Back Navigation to last Fragment

I have two Fragments in my ViewPager as Tabs. These share a toolbar. You get to the SettingsActivity by clicking an Icon on the toolbar. So you can access the SettingsActivity while either Fragment A is the visible one, or Fragment B is the visible one. 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. Without any special code (= current state) it seems to always return to the first Fragment in the ViewPager (ie the most left one). Parent Activity for the Up Navigation is MainActivity, where I have the ViewPager with the 2 Fragments as Tabs.

Use the state saving callback to save the state of your 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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