在Android中,对Fragment
的操做都是经过FragmentTransaction
来执行。而从Fragment
的结果来看,FragmentTransaction
中对Fragment
的操做大体能够分为两类:html
add() replace() show() attach()
remove() hide() detach()
对于每一组方法,虽然最后产生的效果相似,但方法背后带来的反作用以及对Fragment的生命周期的影响都不尽相同。android
只有在Fragment
数量大于等于2的时候,调用add()
仍是replace()
的区别才能体现出来。当经过add()
连续两次添加Fragment
的时候,每一个Fragment
生命周期中的onAttach()-onResume()
都会被各调用一次,并且两个Fragment
的View
会被同时attach
到containerView
。segmentfault
一样,退出Activty
时,每一个Fragment
生命周期中的onPause()-onDetach()
也会被各调用一次。api
但当使用replace()
来添加Fragment
的时候,第二次添加会致使第一个Fragment
被销毁,即执行第二个Fragment
的onAttach()
方法以前会先执行第一个Fragment
的onPause()-onDetach()
方法,同时containerView
会detach第一个Fragment
的View
。app
调用show() & hide()
方法时,Fragment
的生命周期方法并不会被执行,仅仅是Fragment
的View
被显示或者隐藏。并且,尽管Fragment
的View
被隐藏,但它在父布局中并未被detach,仍然是做为containerView
的childView
存在着。相比较下,attach() & detach()
作的就更完全一些。一旦一个Fragment
被detach()
,它的onPause()-onDestroyView()
周期都会被执行。ide
同时Fragment
的View
也会被detach
。在从新调用attach()
后,onCreateView()-onResume()
周期也会被再次执行。布局
其实看完上面的分析,remove()
方法基本也就明白了。相对应add()
方法执行onAttach()-onResume()
的生命周期,remove()
就是完成剩下的onPause()-onDetach()
周期。动画
除了上面这些核心的api外,FragmentTransaction
还提供了更多的方法以丰富Fragment
的操做,如为Fragment
的显示和隐藏添加动画。具体使用方法能够参阅api文档。
spa
http://developer.android.com/reference/android/app/FragmentTransaction.htmlcode