Delete one specific fragment from the Android backstack-ThrowExceptions

Exception or error:

For a android tablet application I use 2 fragments. One on the left side on the screen and one on the right side. When you click on a button at the right fragment, another fragment wil be added on the top of the right fragment. This fragment is added to the backstack.

FragmentTransaction ft = getFragmentManager().beginTransaction(); 
ft.add(R.id.fragmentlayout, fragment2);
ft.addToBackStack("Fragment2");
ft.commit();

The backstack is now:

[fragment 1] -> [fragment 2]

On the left side is also a button that opens a fragment on top of the left fragment (same as fragment2) and adds it to the backstack. The backstack is now

[fragment 1] -> [fragment 2] -> [fragment 3]

On fragment 2 is a button to close that fragment.

getFragmentManager().popBackStack("Fragment2", FragmentManager.POP_BACK_STACK_INCLUSIVE);

The problem is when I only want to close [fragment 2], [fragment 3] will also be destroyed. I can remove the fragment manualy by calling

FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment2).commit();

But the backstack will remain

[fragment 1] -> [(ghost) fragment 2] -> [fragment 3]

So you need to press back one time more to close the application.

Is there a way to only remove [fragment 2] from the backstack and leave [fragment 3] on the screen?

How to solve:

You could simply make your own back stack and override onBackPressed() and handle it in any fashion you see fit. I don’t think there is any other way to achieve the desired behavior.

Your own back stack could simply be an ArrayList of tags for your fragments.

###

I just answered a similar question, so here’s a link to that answer.

The implementation allows you to remove a Fragment from anywhere in the backstack and this is achieved by using refrection to modify the internal variables that store the backstack information in FragmentManagerImpl and BackStackRecord.

Although I do not encourage the use of it, I hope it helps.

###

This solution only works for your case.
You needn’t put Fragment2 into backstack.What you can do is removing the code ‘ft.addToBackStack(“Fragment2”);’.
The Fragment2 is not in the stack.So you close the Fragment2, and leave [fragment 3] on the screen.

###

You can create your own fragment manager/observer. It will be just a simple list or map inside. Track them using tag or simply class name (getClass). This way you’ll be able to avoid new fragment creation and reuse cached one, thus controlling your memory consumption.
You will also be able to manipulate fragments the way you want (override onBackPressed and push which ever fragment you like), instead of using only the way Google says it should/can be done.

Leave a Reply

Your email address will not be published. Required fields are marked *