Why does FragmentTwo disappear from the backstack in the following situation:
- My app has a
FragmentcalledFragmentOnein anActivity. FragmentOneholds aButton. When clicked, it launchesFragmentTwo, which is added to theFragmentbackstack.FragmentTwohas aButton, which when clicked adds two tabs to theActionBarlinked to twoFragments,FragmentThreeandFragmentFour.FragmentThreeis visible.- If I now click the back button, I expected to see
FragmentTwo. Instead, I seeFragmentOne. Where didFragmentTwogo?
Before I override onKeyDown() and start implementing my own backstack for Fragments I wanted to ask if there is something obvious I am missing? Note there is no configuration change happening when testing this.

Details:
FragmentOne’s button click handler contains:
FragmentTransaction ft = getFragmentManager().beginTransaction();
FragmentTwo fragment = new FragmentTwo();
ft.addToBackStack(null);
ft.replace(android.R.id.content, fragment).commit();
FragmentTwo button click is handled in the Activity:
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
FragmentFour fragmentThree = new FragmentThree();
FragmentFive fragmentFive = new FragmentFive();
ActionBar.Tab tab = getActionBar().newTab().setText("Frag 3").setTabListener(new CustomTabListener<FragmentThree>(fragmentThree));
getActionBar().addTab(tab);
tab = getActionBar().newTab().setText("Frag 4").setTabListener(new CustomTabListener<FragmentFour>(fragmentFour));
getActionBar().addTab(tab);
where the tab listener is:
public static class CustomTabListener<T extends Fragment> implements TabListener {
Fragment fragment;
public CustomTabListener(Fragment fragment) {
this.fragment = fragment;
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(android.R.id.content, fragment);
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
I if add more Fragments to backstack before FragmentThree is shown, it is always and only the Fragment immediately before FragmentThree that has disappeared.
When I leave the Tabbed user view by pressing the back key and return to FragmentOne, the tabs are still showing. I understand I need to reset the ActionBar to NAVIGATION_MODE_STANDARD, but it’s not clear why FragmentOne is showing instead of FragmentTwo.
I think the problem is if you build your tabs
gets called and the fragment before is not added to the backstack
did you try to call
in the Fragment Two button handling code.
But you need to implement
onBackPressed()anyway to get rid of the tabs. I think I would make new activity with tabs.