栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

popBackStack()和replace()操作有何区别?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

popBackStack()和replace()操作有何区别?

replace()
做两件事:

  1. 从您指定的容器(C)中删除当前添加的片段(A)
  2. 将新片段(B)添加到同一容器

这两个操作被保存为Backstack记录/事务。请注意,片段A保持

created
状态,并且其视图已损坏。

现在,

popBackStack()
撤消您添加到BackStack的上一个事务。

在这种情况下,这将是2个步骤:

  1. 从C中删除B
  2. 将A加到C

此后,片段B变为

detached
,如果您不保留对其的引用,它将被垃圾回收。

要回答问题的第一部分,没有任何

onCreate()
电话,因为FragmentB保持
created
状态。对问题第二部分的回答要更长一些。

首先,重要的是要了解您实际上并没有添加

Fragments
到Backstack中
FragmentTransactions
。所以,当你认为你“与片段B取代,加入片段A到后面栈”,实际上添加这整个操作堆栈中-即
替代 与B. A的这种替换包括2个动作-删除和Add(添加) 。

然后,下一步是弹出包含此替换的事务。因此,您没有弹出FragmentA,而是反转了“删除A,添加B”,反过来就是“删除B,添加A”。

然后最后一步应该更清楚-FragmentManager不会知道B,因此当您在最后一步通过用B替换A来添加它时,B需要经历其早期生命周期方法-

onAttach()
onCreate()

下面的代码说明了正在发生的事情。

FragmentManager fm  = getFragmentManager();FragmentA fragmentA = new FragmentA();FragmentB fragmentB = new FragmentB();// 1. Show Afm.beginTransaction()  .add(fragmentA, R.id.container)  .commit();// 2. Replace A with B// FragmentManager keeps reference to fragmentA;// it stays attached and created; fragmentB goes // through lifecycle methods onAttach(), onCreate()// and so on.fm.beginTransaction()  .replace(fragmentB, R.id.container)  .addToBackstack(null)  .commit();// 2'. Alternative to replace() methodfm.beginTransaction()  .remove(fragmentA)  .add(fragmentB, R.id.container)  .addToBackstack(null)  .commit();// 3. Reverse (2); Result - A is visible// What happens://   1) fragmentB is removed from container, it is detached now;//      FragmentManager doesn't keep reference to it anymore//   2) Instance of FragmentA is placed back in the container// Now your Backstack is empty, FragmentManager is aware only// of FragmentA instancefm.popBackStack();// 4. Show B// Since fragmentB was detached, it goes through its early// lifecycle methods: onAttach() and onCreate().fm.beginTransaction()  .replace(fragmentB, R.id.container)  .addToBackstack(null)  .commit();


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/496518.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号