FragmentTransaction与Fragment生命周期的关系

来源:互联网 发布:pdb蛋白质数据库 编辑:程序博客网 时间:2024/05/16 18:18

在Android中,对Fragment的操作都是通过FragmentTransaction来执行。而从Fragment的结果来看,FragmentTransaction中对Fragment的操作大致可以分为两类:

  • 显示:add() replace() show() attach()
  • 隐藏:remove() hide() detach()

对于每一组方法,虽然最后产生的效果类似,但方法背后带来的副作用以及对Fragment的生命周期的影响都不尽相同。

add() vs. replace()

只有在Fragment数量大于等于2的时候,调用add()还是replace()的区别才能体现出来。当通过add()连续两次添加Fragment的时候,每个Fragment生命周期中的onAttach()-onResume()都会被各调用一次,而且两个FragmentView会被同时attachcontainerView

同样,退出Activty时,每个Fragment生命周期中的onPause()-onDetach()也会被各调用一次。

但当使用replace()来添加Fragment的时候,第二次添加会导致第一个Fragment被销毁,即执行第二个FragmentonAttach()方法之前会先执行第一个FragmentonPause()-onDetach()方法,同时containerView会detach第一个FragmentView

show() & hide() vs. attach() & detach()

调用show() & hide()方法时,Fragment的生命周期方法并不会被执行,仅仅是FragmentView被显示或者​隐藏。而且,尽管FragmentView被隐藏,但它在父布局中并未被detach,仍然是作为containerViewchildView存在着。相比较下,attach() & detach()做的就更彻底一些。一旦一个Fragmentdetach(),它的onPause()-onDestroyView()周期都会被执行。

同时FragmentView也会被detach。在重新调用attach()后,onCreateView()-onResume()周期也会被再次执行。

remove()

其实看完上面的分析,remove()方法基本也就明白了。相对应add()方法执行onAttach()-onResume()的生命周期,remove()就是完成剩下的onPause()-onDetach()周期。

总结

除了上面这些核心的api外,FragmentTransaction还提供了更多的方法以丰富Fragment的操作,如为Fragment的显示和隐藏添加动画。具体使用方法可以参阅api文档。

0 0
原创粉丝点击