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
The backstack contains records about transactions, not fragments itself. So you should not add first transaction's record (null -> fragA) to backstack. And all other transaction's record should be added to backstack. In this case, then you preform
popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
android removed all fragments except fragA, because there isn't any records about how fragA was added.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...
you can later determine which fragment to show when the back button is pressed...
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 theFragment
class...BTW, I'm talking about native fragments here, not support library's fragment.1) Add First Fragment using below code
2) Add Second Fragment From First fragment using below code
3) Add Third Fragment From Second fragment using below code
4) Add Forth Fragment From Third fragment using below code
5) onBackPressed() please write below code
After looking through many posts, I figured it out this way:
in fragC => fragD method, do two transactions:
1 clear back stacks, fragC => fragA
2 fragA => fragD
But in this way, the original state of fragA may be destroyed.
Now pressing back on fragD goes back to fragA.
I have done following way. Clear all fragment then add first home fragment
Only a few days ago I start learning about fragments in Android. And I faced with this problem too. Here I show my solution and how I resolve this. Please, fix if my code is not right. What we have at this time? Acivity, many fragments and their backstack. We want open every fragment from Drawer menu and clear all other fragments from backstack. But, we must hold only one Home fragment. When we stay on Home fragment and user press Back button app is goeing closing.
Activity.class
And on click on drawer menu item