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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With