PopBackStack but keep the first fragment in android
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 preformpopBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
android removed all fragments except fragA, because there isn't any records about how fragA was added.
E.g. you can do following:
- add fragA without adding it to backStack. So it always be in
activity, and won't react on back button. - when you open fragD you should clear fragment BackStack. So when you press back button from D frag you go back to A.
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.