Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete one specific fragment from the Android backstack

Tags:

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?

like image 356
Bas Avatar asked Mar 27 '13 16:03

Bas


1 Answers

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.

like image 152
Warpzit Avatar answered Oct 30 '22 16:10

Warpzit