如何从Android中的后堆栈中删除特定片段 [英] How to delete a specific fragment from back stack in android

查看:56
本文介绍了如何从Android中的后堆栈中删除特定片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于从后堆栈中删除特定片段的问题.我的情况是这样的:将Fragment-1替换为Fragment-2,然后将Fragment-2替换为Fragment-3.

I have a problem about removing a specific fragment from back stack.My scenario is like this.Fragment-1 is replaced with Fragment-2 and then Fragment-2 is replaced with Fragment-3.

呼叫顺序; Fragment-1-> Fragment-2-> Fragment-3.

Calling order; Fragment-1-->Fragment-2-->Fragment-3.

当Fragment-3显示在屏幕上,然后单击后退"按钮时,我想去

When Fragment-3 is on the screen and then back button is clicked, i want to go

Fragment-1.这意味着我想从后堆栈中删除Fragment-2.

Fragment-1.That means i want to delete Fragment-2 from back stack.

如何执行此操作?

推荐答案

在后堆栈中,您没有Fragment,但是没有FragmentTransaction.当您popBackStack()时,将再次应用事务,但将其向后应用.这意味着(假设您每次addToBackStackTrace(null))您的后备箱中有

In the backstack you don't have Fragments, but FragmentTransactions. When you popBackStack() the transaction is applied again, but backward. This means that (assuming you addToBackStackTrace(null) every time) in your backstack you have

1->2
2->3

如果您不将第二笔交易添加到Backstack中,则结果是您的Backstack就是

If you don't add the second transaction to the backstack the result is that your backstack is just

1->2

,因此按下后退按钮将导致执行2->1,由于片段2不存在而导致错误(您在片段3上).
最简单的解决方案是先将Backstack弹出,然后再从2变为3

and so pressing the back button will cause the execution of 2->1, which leads to an error due to the fragment 2 not being there (you are on fragment 3).
The easiest solution is to pop the backstack before going from 2 to 3

//from fragment-2:
getFragmentManager().popBackStack();
getFragmentManager().beginTransaction()
   .replace(R.id.container, fragment3)
   .addToBackStack(null)
   .commit();

我在这里做的是这些:从片段2回到片段1,然后直接到达片段3.这样,后退按钮会将我从3再次带到1.

What I'm doing here is these: from fragment 2 I go back to fragment 1 and then straight to fragment 3. This way the back button will bring me again from 3 to 1.

这篇关于如何从Android中的后堆栈中删除特定片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆