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?

asked May 31 '11 at 10:49
biquillo
1,66252133
 
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

answered Jun 1 '11 at 8:05
PJL
8,13485659
 
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);
answered Oct 18 '14 at 12:19
 
    
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();
}
answered Mar 4 at 9:01
dbm
4,80742545
 
    
....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();
}
answered Oct 14 '14 at 12:45
 

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.

answered Aug 31 at 5:16
Nicks
1,4591024
 

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)
answered May 14 at 9:20
 

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();
}
}
});
}
answered Oct 28 '14 at 15:11
saulobrito
2,3771913
 

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);
answered Jul 30 at 9:37
Md Mohsin
496419
 

[转]使用popBackStack()清除Fragment的更多相关文章

  1. Android Fragment 解析和使用

    Android Fragment的生命周期和Activity类似,实际可能会涉及到数据传递,onSaveInstanceState的状态保存,FragmentManager的管理和Transactio ...

  2. Fragment响应返回键

    Activty可以直接响应返回键,而Fragment却不行,可用如下方式: 创建一个抽象类BackHandledFragment,该类中有一个抽象方法onBackPress(),所有BackHandl ...

  3. Android 开发 之 Fragment 详解

    本文转载于 : http://blog.csdn.net/shulianghan/article/details/38064191 本博客代码地址 : -- 单一 Fragment 示例 : http ...

  4. 让Fragment监听返回键

    Activity可以很容易的得到物理返回键的监听事件,而Fragment却不能.所以使用到了以下的方法. 首先创建一个抽象类BackHandledFragment,该类有一个抽象方法onBackPre ...

  5. Fragment 总结

    本博客代码地址 : -- 单一 Fragment 示例 : https://github.com/han1202012/Octopus-Fragement.git -- 可复用的 Fragment 示 ...

  6. Android开发之Fragment的介绍、使用及生命周期

    Fragment官网介绍-http://developer.android.com/guide/components/fragments.html 郭大神的使用实例文章:http://blog.csd ...

  7. Android学习笔记(五)Fragment简介

    Fragment是在Android 3.0 (API level 11)中引入的Activity的子模块.初衷是为了适应大屏幕的平板电脑,我们只需要使用Fragment对UI组件进行分组.模块化管理, ...

  8. 【Android 应用程序开发】 Fragment 详细说明

    笔者 : 汉书亮 转载请著名出处 : http://blog.csdn.net/shulianghan/article/details/38064191 本博客代码地址 : -- 单一 Fragmen ...

  9. 【Android 应用开发】 Fragment 详解

    作者 : 韩曙亮 转载请著名出处 : http://blog.csdn.net/shulianghan/article/details/38064191 本博客代码地址 : -- 单一 Fragmen ...

随机推荐

  1. JS跳转页面常用的几种方法

    第0种:(常用) function triggerAOnclick(){ window.open("http://localhost/jwxt/forward/2TrainSchemeDat ...

  2. Java企业级电商项目架构演进之路 Tomcat集群与Redis分布式

    史诗级Java/JavaWeb学习资源免费分享 欢迎关注我的微信公众号:"Java面试通关手册"(坚持原创,分享各种Java学习资源,面试题,优质文章,以及企业级Java实战项目回 ...

  3. BurpSuite 设置Hostname Resolution

    #写在前面 这种情况你可能遇到过: 对方用了CDN, 你查到了对方真实IP, 但还不能100%肯定. 这时候, 最好的测试就是 win/linux修改HOST文件 Win重启电脑 Linux重启网络 ...

  4. py,pyc,pyw文件的区别和使用

    熟悉python编程的都知道,python三种最常见的py文件格式,.py,.pyc,.pyw,下面说一说它们各自的使用. py文件 python最常见的文件,是python项目的源码: 文件执行时l ...

  5. fastDFS 命令笔记【转】

    端口开放 这是命令运行的前提 iptables -I INPUT -p tcp -m state –state NEW -m tcp –dport 22 -j ACCEPT iptables -I I ...

  6. TreeSet之定制排序和自然排序

    TreeSet的几大特点: 1.TreeSet中存储的类型必须是一致的,不能一下存int,一下又存string 2.TreeSet在遍历集合元素时,是有顺序的[从小到大](我的理解,如果存的字母,按字 ...

  7. u-boot引导内核过程

    目标板:2440 u-boot引导内核启动时,传入内核的参数为bootcmd=nand read.jffs2 0x30007FC0 kernel; bootm 0x30007FC0 一.nand re ...

  8. MVC – 4.mvc初体验(2)

    5.显示学员列表 效果 数据表 5.1 首先,在文件夹Models新建一个新建项(W),选择ADO.NET 实体数据模型 (SingleTest.edmx) 5.2 建一个控制器,StudentsCo ...

  9. gym101431B

    以此纪念我都快忘了的后缀自动机(捂脸) 不过这题有两种做法: 用后缀自动机,先把原串再接遍中间加入特殊连接字符再把原串反接两遍,对这个新构造出的串做后缀自动机.(或者直接建立广义后缀自动机) 下面只要 ...

  10. [实战]MVC5+EF6+MySql企业网盘实战(14)——思考

    写在前面 从上面更新编辑文件夹,就一直在思考一个问题,之前编辑文件夹名称,只是逻辑上的修改,但是保存的物理文件或者文件夹名称并没有进行修改,这样就导致一个问题,就是在文件或者文件夹修改名称后就会找不到 ...