سؤال

How to clear BackStackEntries in FragmentManager ? This is the code I use to change my fragment object:

FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
Fragment homeFragment = new Home();
fragmentTransaction.replace(R.id.mainFragement, homeFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

In a particular situation I need to remove the complete backstack entries. I didn't find any particular method for that in fragment manager. Do you have any ideas?

هل كانت مفيدة؟

المحلول

I have been working on a method that I think does what you're asking to do, but the only thing I have been able to figure out from the documentation is whether or not this method just empties the BackStack or if there's any implication on the View container. Basically, it finds the entry located at the top of the stack and deletes everything, including that entry. If someone else thinks that there are negative implications let me know because I'd be very curious:

public static void clearBackStack(FragmentManager manager){
    int rootFragment = manager.getBackStackEntryAt(0).getId();
    manager.popBackStack(rootFragment, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}

نصائح أخرى

This works fine for me:

clearFragments(FragmentManager fm) {
    while (fm.popBackStackImmediate());
}

You are right, there is no way of clearing the stack as far as I can read through the documentation.

This is a big issue. Try uploading the issue to Android's issue tracker and I hope someone looks at it. I am still waiting for mine.

This is quite a hack but you can try finishing your Activity and starting it again. It might clear the stack.

If you want to clear all the back stack probably is because you are going to do something that is not related with previous context. In that case you should launch a new Activity.

As I'm starting to understand, with Fragments, Activities will work as containers of Fragments. You should try to keep independency between Fragments, while organizing them in Activities based on their context.

In your case, when the particular situation happens, you can launch a new Activity and place the desired fragment on this new Activity instead of place it in the old-Activity. This new Activity will handle the new stack of fragments. That way you will also have your code a bit more encapsulated, no?

Take a look to this explanatory reply: CommonsWare reply

hope it helps!

Did you try popBackStack() calls in Fragment manager ?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top