Currently I have one activity, and fragments are being added to it (search, song details, settings, etc). I implemented side based menu navigation, so now, as a side effect, teh
This is an old question but my answer might help someone.
Why not checking if the fragment is in the stack and pop it? This way you wouldn't have to worry with back stack size (unless you have a lot of fragments).
String backStateName = fragment.getClass().getName();
boolean fragmentPopped = false;
try {
// true if fragment is in the stack
fragmentPopped = fragmentManager.popBackStackImmediate(backStateName, 0);
} catch (Exception e) {
e.printStackTrace();
}
FragmentTransaction ft = fragmentManager.beginTransaction();
if ( !fragmentPopped ) { //fragment not in back stack, add it...
ft.setTransition( FragmentTransaction.TRANSIT_FRAGMENT_FADE );
ft.replace(R.id.main, fragment);
ft.addToBackStack( backStateName );
try {
ft.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
You can programatically control the number of Fragments in your BackStack:
FragmentManager fm = getActivity().getSupportFragmentManager();
if(fm.getBackStackEntryCount() > 10) {
fm.popBackStack(); // remove one (you can also remove more)
}
Simply check how many Fragments there are in your Backstack and remove if there is an "overflow".
If you want to remove specific Fragments from the BackStack, you will have to implement your own BackStack and override onBackPressed(). Since the Fragment BackStack is a Stack (as the name indicates), only the top element (the last added) can be removed, there is no possibility of removing Fragments in between.
You could for example use
ArrayList<Fragment>
to realize your own stack. Simply add and remove Fragments from that "stack" (it's not really a stack anymore) whenever you desire and handle the loading of previous fragments by overriding the onBackPressed() method.