如果我加载了 fragment , fragment A,并用 fragment B 替换该 fragment ,将 fragment A 添加到后台堆栈,如下所示:
public void replaceFragment(Fragment frag, String fragTag) {
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.fragmentContainer, frag, fragTag);
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.commit();
}
然后从 fragment B 我调用:
popBackStackImmediate();
因此再次加载 fragment A。 fragment B 会发生什么?在我的代码中,我正在创建一个新的 Fragment B 对象并使用我的 replaceFragment() 方法加载它,然后重复该过程。每次我用 B 替换 A 并调用 popBackStack() 时,我是在创建一堆 fragment B,还是在调用 popBackStack 时 B 被销毁?谢谢。
最佳答案
popBackStack()
反转您的最后一笔交易,在您的情况下,是一个replace
交易。
FragmentTransaction 文档对此非常清楚。替换的作用:
Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.
因此,如果添加了 A 并且您调用了 replace(container, B)
,那么您实际上是在调用
移除(A)
添加(B)
就是说,使用 popBackStack()
逆转这个交易本质上是:
移除(B)
添加(A)
A 或 B 的哪个实例,你问,这取决于你如何使用你的方法。据我所知,remove
d fragment 将被销毁(除非您保留对它的引用)。如果您每次都调用 new Fragment()
,那么答案很简单 - 您正在创建大量实例。
FragmentTransaction
API 提供了替代方法来处理像您这样的情况,在这种情况下您必须多次切换 A
和 B
。这些也有据可查。例如,您可以使用 hide()
和 show()
隐藏 fragment A 并显示 fragment B,而无需收集 A 垃圾并创建不必要的新实例。
此外,您可以使用 detach()
和 attach()
. show 和 hide 的不同之处在于,这种方式每次都会销毁和重新创建 fragment View (注意:不是 fragment 实例)。另一方面,隐藏和显示只是让 View 不可见而不破坏它。
关于android - 调用 popBackStack() 后当前 fragment 会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35046192/