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, tehre's no limit to how many Fragments get added to the Backstack. Is there any way I can limit the number of fragments, or remove older entries? Each song details fragment for instance, has a recommended song list, and through that you can go to another song details fragment. It's easily possible to have 30 fragments in the backstack, which if you have DDMS open, you can see the heap size slowly (but surely) increasing.
Edit: One thing I did try to do is if a User clicked one of the side menu options, if that fragment is already in the backstack try to go back to that fragment instead of instantiating a new one, but of course, if a user is on a Song Details page, then he would expect pressing back would take him to that Fragment so that won't work.
Edit 2: This is my addFragment method (along with Phil's suggestion):
public void addFragment(Fragment fragment) {
FragmentManager fm = getSupportFragmentManager();
if(fm.getBackStackEntryCount() > 2) {
fm.popBackStack();
}
fm.beginTransaction()
.replace(R.id.fragment_container, fragment).addToBackStack("")
.commit();
}
I just tried it, and assuming my Fragment history is: A->B->C->D, going back from D, goes B->A->exit.
I just went 8 levels deep to test: A->B->C->D->E->F->G->H, and going back from H, same thing happened: H->B->A->exit.
All Fragments are getting added through that method above. What I would like to see is: H->G->F->exit.