Fragment与Activity的生命周期关系:
刚打开Activity:
Fragment onAttach > Fragment onCreate > Fragment onCreateView
> Activity onCreate > Fragment onActivityCreated
> Activity onStart > Fragment onStart >
Activity onResume > Fragment onResume
关闭Activity:
Fragment onPause > Activity onPause
> Fragment onStop > Activity onStop
> Fragment onDestroyView > Fragment onDestroy > Fragment onDetach > Activity onDestroy
进入下一个Activity:
Fragment onPause > Activity onPause
> Fragment onStop > Activity onStop
返回到当前Activity:
Activity onRestart > Activity onStart > Fragment onStart
> Activity onResume > Fragment onResume
添加Fragment:
onCreate > onCreateView > onActivityCreated > onStart > onResume
Fragment添加后是否加入返回栈,生命周期都一样,pop即完全移除到onDetach
移除Fragment(未添加到返回栈):
onPause > onStop > onDestroyView > onDestroy > onDetach
移除Fragment(添加到返回栈):
onPause > onStop > onDestroyView
使用popBackStack恢复移除的Fragment:
onCreateView > onActivityCreated > onStart > onResume
写在xml中的静态Fragment,移除后虽然变成null,但视觉上并不会消失;只有在代码中动态添加的Fragment,移除后才会真正消失
FragmentTransaction调用addToBackStack(null)可以在commit之前任何时候,包括在实施增删改Fragment之前调用,之后popBackStack的效果都是一样的