Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?
Well there are a few ways to go about this depending on the intended behavior, but this link should give you all the best solutions and not surprisingly is from Dianne Hackborn
http://groups.google.com/group/android-developers/browse_thread/thread/d2a5c203dad6ec42
Essentially you have the following options
- Use a name for your initial back stack state and use
FragmentManager.popBackStack(String name, FragmentManager.POP_BACK_STACK_INCLUSIVE)
. - Use
FragmentManager.getBackStackEntryCount()
/getBackStackEntryAt().getId()
to retrieve the ID of the first entry on the back stack, andFragmentManager.popBackStack(int id, FragmentManager.POP_BACK_STACK_INCLUSIVE)
. FragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
is supposed to pop the entire back stack... I think the documentation for that is just wrong. (Actually I guess it just doesn't cover the case where you pass inPOP_BACK_STACK_INCLUSIVE
),
The other clean solution if you don't want to pop all stack entries...
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(R.id.home_activity_container, fragmentInstance).addToBackStack(null).commit();
This will clean the stack first and then load a new fragment, so at any given point you'll have only single fragment in stack
Thanks to Joachim answer, I use the code to clear all back stack entry finally.
// In your FragmentActivity use getSupprotFragmentManager() to get the FragmentManager.
// Clear all back stack.
int backStackCount = getSupportFragmentManager().getBackStackEntryCount();
for (int i = 0; i < backStackCount; i++) {
// Get the back stack fragment id.
int backStackId = getSupportFragmentManager().getBackStackEntryAt(i).getId();
getSupportFragmentManager().popBackStack(backStackId,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
} /* end of for */