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.
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();
}