Simple question but seems impossible to answer... How to clear fragmentManager back stack without poping fragments?
I understand it like this:
Back stack entries = list of previosly saved transactions with addToBackStack command. For example: "replace Fragment 1 with Fragment 2".
popBackStack = do last saved transatcion reverse. For example: "replace Fragment 2 with Fragment 1".
Let's say i did first transaction: F1->F2 and added this transaction to back stack. When I press back button now the F2->F1 will happen.
OK...But..
I've changed my mind and I want to clear the back stack. I want the user to work with F2 fragment but when he/she presses back button the Activity should close like the back stack is empty.
I need something like:
for(int i=0;i<getFragmentManager().getBackStackEntryCount();i++){
getFragmentManager().getBackStackEntryAt(i).remove();
}
EDITED I've tried to ask simple question to complex situation and I get simple answer ;) Abhishek Patel's answer is very good but it is not what I was looking for. Still it's a good answer.
Just to clarify: Back stack in android is not fully editable list like:
We can't do "Remove transaction 3" to make:
We can't clear all backstack and keep last visible fragment alive.
We can delete backstacks records to certain position like: "Remove everything to Transaction 2" to get:
On screen you'll see the efect of transaction 2.
WHY DID I NEED THIS?
I thought that I can make a Fragment which will be 'Main fragment'.This main fragment will use an Interface to tell whatever activity it is in that this boss fragment is shown now, and whatever happens before - is not important anymore.
(F)-Fragment, (A)-Activity
(F) - Hey dude. I'm the boss and I'm visible and attached to you. Please clear your backstack for me but keep my transaction which brought me here.
(A) - Sorry man...You should have told me before your transaction to clear my backstack so I can add your transaction on top of fresh new backstack.
popBackStack will just revert your last FragmentTransaction . If you use FragmentTransaction. add , popBackStack will just call FragmentTransacetion.
addToBackStack. Add this transaction to the back stack. This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack.
Try This it may be help
public void clearBackstack() {
BackStackEntry entry = getSupportFragmentManager().getBackStackEntryAt(
0);
getSupportFragmentManager().popBackStack(entry.getId(),
FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().executePendingTransactions();
}
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