上图中,蓝色的区域我们会放置一个fragment记为FragmentLifecycle3,红色区域我们用样也会放置一个FragmentLifecycle。
操作一:我们将FragmentLifecycle替换为FragmentLifecycle2,同时将FragmentLifecycle加入到回退栈中 addToBackStack(null),
操作二:当我们按下返回键的时候会出现什么现象呢?
06-25 17:13:45.040 10373-10373/com.lj.test I/com.lj.test.FragmentLifecycle2: onPause
onStop
06-25 17:13:45.041 10373-10373/com.lj.test I/com.lj.test.FragmentLifecycle2: onDestroyView
06-25 17:13:45.042 10373-10373/com.lj.test I/com.lj.test.FragmentLifecycle2: onDestroy
onDetach
06-25 17:13:45.042 10373-10373/com.lj.test I/com.lj.test.FragmentLifecycle: onCreateView
06-25 17:13:45.059 10373-10373/com.lj.test I/com.lj.test.FragmentLifecycle: onViewCreated
onActivityCreated
onStart
06-25 17:13:45.060 10373-10373/com.lj.test I/com.lj.test.FragmentLifecycle: onResume
观察上面的日志:
先是调用了FragmentLifecycle2的剩余生命周期然后死亡了,然后紧接着调用了FragmentLifecycle的的onCreateView、onViewCreated、onActivityCreated、onStart、onResume方法
我们分析上面的调用发现FragmentLifecycle3的生命周期没有调用,这是为啥呢?为啥单单会是FragmentLifecycle2被死亡了呢?
答:这是由于我们的回退栈的存在才产生的这种现象,当我们按下返回键的时候,会将回退栈的栈顶元素弹出,弹出的元素会再次替换之前的id位置,这样的话,我弹出的FragmentLifecycle会替换掉当前站在它的id位置的FragmentLifecycle2。这样的话,我们就清楚了,为什么单单只是FragmentLifecycle2被回退栈中的元素替换掉了,而我们的FragmentLifecycle3没有收到影响
操作三:当我们继续按下返回键
06-25 17:26:25.092 10373-10373/com.lj.test I/com.lj.test.FragmentLifecycle3: onPause
06-25 17:26:25.092 10373-10373/com.lj.test I/com.lj.test.FragmentLifecycle: onPause
06-25 17:26:25.272 10373-10373/com.lj.test I/com.lj.test.FragmentLifecycle3: onStop
06-25 17:26:25.272 10373-10373/com.lj.test I/com.lj.test.FragmentLifecycle: onStop
06-25 17:26:25.272 10373-10373/com.lj.test I/com.lj.test.FragmentLifecycle3: onDestroyView
06-25 17:26:25.273 10373-10373/com.lj.test I/com.lj.test.FragmentLifecycle3: onDestroy
onDetach
06-25 17:26:25.273 10373-10373/com.lj.test I/com.lj.test.FragmentLifecycle: onDestroyView
06-25 17:26:25.274 10373-10373/com.lj.test I/com.lj.test.FragmentLifecycle: onDestroy
onDetach
通过log我们发现: FragmentLifecycle和FragmentLifecycle3都死亡了。
解释:这是是由于我们的回退栈中已经没有fragment了,所以当我们按下手机返回键,此时Activity就会被销毁,同时我们所有的fragment会跟随宿主的生命周一一并销毁。
拓展:我们在使用谷歌提供的MvvM框架的时候使用到的ViewModel的生命周期也是借用Fragment来实现的。
每个Activity通过sHolderFragmentManager持有一个HolderFragment,这个HolderFragment中存放了一个ViewModelStore类的对象mViewModelStore,这个对象中缓存真我们的ViewModel对象。
所以我们的ViewModel的生命周期通过HolderFragment巧妙的绑定到了Activity的生命周期中。
我们只是通过现象分析的出了上面关于Fragment的结论,我们还需要通过源代码来查证,下一篇文章中我会通过源代码来进一步说明。