I am working on fragment transaction, and the backstack is like this:
fragA => fragB => fragC => fragD
I would like to return to fragA after back fromn the fragD
fragD => onBackPress => fragA
So, I tried code like:
getChildFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
but it clear all the backstack , how can I keep the first fragment in the backstack? Thanks a lot
popBackStack() will remove current fragment and replace it with the last one from the stack. For this to work you need to do addToBackstack() on the last fragment transaction.
add() - (create and) add a Fragment B and it overlap Fragment A, which is still active in the background. remove() - can be used to remove Fragment B and return to A. Fragment B will be recreated when called later on.
Calling addToBackStack() commits the transaction to the back stack. The user can later reverse the transaction and bring back the previous fragment by pressing the Back button. If you added or removed multiple fragments within a single transaction, all of those operations are undone when the back stack is popped.
Explanation: MainFragment -> Fragment A -> Fragment B (this is added to backstack) -> Fragment C -> MainFragment (clear backstack ).
E.g. you can do following:
P.S. There are other ways how to do what you want. It depends...
Because the "back stack" has a stack-like behaviour...last-in, first-out...the last fragment you added to the back stack will be popped out of the back stack first. You will need to implement the behaviour you required manually by specifying your own. This is not that hard using the FragmentManager
class methods.
If you "tag" your fragments as you add them to the transaction...
fragmentTransaction.add(new FragmentA(), "FragmentA_Tag");
you can later determine which fragment to show when the back button is pressed...
FragmentA f = fragmentManager.findFragmentByTag("FragmentA_Tag");
if(f != null){
f.show();
}
How you determine which fragment to show it's entirely up to you. You can keep track of the current visible fragment or you can use the isHidden
method of the Fragment
class...BTW, I'm talking about native fragments here, not support library's fragment.
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