[转]使用popBackStack()清除Fragment

I ported my Android app to honeycomb and I did a big refactor in order to use fragments. In my previous version, when I pressed the Home button I used to do a ACTIVITY_CLEAR_TOP in order to reset the back stack.

Now my app is just a single Activity with multiple fragmens, so when I press the Home button I just replace one of the fragments inside it. How can I clear my back stack without having to use startActivity with the ACTIVITY_CLEAR_TOP flag?

shareimprove this question
 
23  
You refactored your entire app to include Fragments? You sir, are a boss. – Subby Mar 13 '14 at 9:45
    
Avoid using back stacks! it doesn't really help with the overall efficiency! use plain replace() or even better remove/add every time you want to navigate! Check my post on stackoverflow.com/questions/5802141/… – stack_ved Sep 29 '14 at 6:02

8 Answers

up vote167down voteaccepted

I posted something similar here

From Joachim's answer, from Dianne Hackborn:

http://groups.google.com/group/android-developers/browse_thread/thread/d2a5c203dad6ec42

I ended up just using:

FragmentManager fm = getActivity().getSupportFragmentManager();
for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {    
    fm.popBackStack();
}

But could equally have used something like:

FragmentManager.popBackStack(String name, FragmentManager.POP_BACK_STACK_INCLUSIVE)

Which will pop all states up to the named one. You can then just replace the fragment with what you want

shareimprove this answer
 
1  
But this has huge side effects, doesn't it? – Peter Ajtai Nov 27 '11 at 6:38
7  
Well, it's equivalent to hitting the back button one or more times, so it changes the fragment that is currently visible. (At least when I've tried it) – Peter Ajtai Nov 28 '11 at 0:02 
5  
I am having the same issue as peter. I'd like to clear all of the fragments out rather than having it cycle through them which has lots of implications. For example, you will hit lifecycle events that you don't need to by popping every fragment off of the stack sequentially. – Brian Griffey Jan 16 '12 at 16:24
101  
To go to top simply use: fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); – Warpzit Jan 7 '13 at 10:35
24  
For what it's worth, using fragmentManager. popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); worked even better for me as it prevented the fragment animations from executing – roarster Sep 19 '13 at 19:49 
 

To make an answer for Warpzit comment and make it easiere to find for others, use:

fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
shareimprove this answer
 
    
This worked for me. It seems like a nice one liner too. – ShawnV Jan 10 at 21:39
5  
I believe popping all fragments from the backstack this way has been broken in the latest v7-appCompat library when using AppCompatActivity. After updating my app to the lastest v7-appCompat library (21.0.0) and extending the new AppCompatActivity, popping fragments in the above manner is leaving some fragments in the backstack record of the FragmentManager. I'd advise against using this. – dell116 May 1 at 18:52 

With all due respect to all involved parties; I'm very surprised to see how many of you could clear the entire fragment back stack with a simple

fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

According to Android documentation (regarding the name argument - the "null" in the claimed working proposals).

If null, only the top state is popped

Now, I do realize that I'm lacking knowledge of your particular implementations (like how many entries you have in the back stack at the given point in time), but I would bet all my money on the accepted answer when expecting a well defined behaviour over a wider range of devices and vendors:

(for reference, something along with this)

FragmentManager fm = getFragmentManager(); // or 'getSupportFragmentManager();'
int count = fm.getBackStackEntryCount();
for(int i = 0; i < count; ++i) {    
    fm.popBackStack();
}
shareimprove this answer
 
    
....this....is most likely the best way to do it. – dell116 May 1 at 18:50

Accepted answer was not enough for me. I had to use :

FragmentManager fm = getSupportFragmentManager();
int count = fm.getBackStackEntryCount();
for(int i = 0; i < count; ++i) {
    fm.popBackStackImmediate();
}
shareimprove this answer
 

I just wanted to add :--

Popping out from backstack using following

fragmentManager.popBackStack()

is just about removing the fragments from the transaction, no way it is going to remove the fragment from the screen. So ideally, it may not be visible to you but there may be two or three fragments stacked over each other, and on back key press the UI may look cluttered,stacked.

Just taking a simple example:-

Suppose you have a fragmentA which loads Fragmnet B using fragmentmanager.replace() and then we do addToBackStack, to save this transaction. So the flow is :--

STEP 1 -> FragmentA->FragmentB (we moved to FragmentB, but Fragment A is in background, not visible).

Now You do some work in fragmentB and press the Save button—which after saving should go back to fragmentA.

STEP 2-> On save of FragmentB, we go back to FragmentA.

STEP 3 ->So common mistake would be... in Fragment B,we will do fragment Manager.replace() fragmentB with fragmentA.

But what actually is happenening, we are loading Fragment A again, replacing FragmentB . So now there are two FragmentA (one from STEP-1, and one from this STEP-3).

Two instances of FragmentsA are stacked over each other, which may not be visible , but it is there.

So even if we do clear the backstack by above methods, the transaction is cleared but not the actual fragments. So ideally in such a particular case, on press of save button you simply need to go back to fragmentA by simply doing fm.popBackStack() or fm.popBackImmediate().

So correct Step3-> fm.popBackStack() go back to fragmentA, which is already in memory.

shareimprove this answer
 

Clear backstack without loops

String backStackEntryName = getSupportFragmentManager().getBackStackEntryAt(0).getName();
getSupportFragmentManager().popBackStack(name, FragmentManager.POP_BACK_STACK_INCLUSIVE);

Where name is the addToBackStack() parameter

getSupportFragmentManager().beginTransaction().
                .replace(R.id.container, fragments.get(titleCode))
                .addToBackStack(name)
shareimprove this answer
 

I got this working this way:

public void showHome() {
    getHandler().post(new Runnable() {
        @Override
        public void run() {
            final FragmentManager fm = getSupportFragmentManager();
            while (fm.getBackStackEntryCount() > 0) {
                fm.popBackStackImmediate();
            }
        }
    });
}
shareimprove this answer
 

Works for me and easy way without using loop:

 FragmentManager fragmentManager = getSupportFragmentManager();
 //this will clear the back stack and displays no animation on the screen
 fragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
shareimprove this answer
 
posted @ 2015-11-02 02:27  yunlvrensheng  阅读(4439)  评论(0编辑  收藏  举报