Fragment生命周期以及 常见的切换生命周期发生的变化
首先介绍下,Activity和Fragment生命周期的对比与Fragment的生命周期,如图:
Fragment相关操作对生命周期的影响
添加Fragment可以分为静态添加和动态添加两大类。
- 静态添加是在XML中直接添加Fragment,简单方便,缺点是添加之后不能在删除。动态添加是在代码中
- FragmentManger使用一系列FragmentTransaction事务操作动态控制,灵活多变。一般都是使用动态添加,下面就讲讲动态添加有关的生命周期。
-
add:onAttach->onCreate->onCreateView->onActivityCreated->onStart->onResume
-
remove:onPause->onStop->onDestroyView->onDestroy->onDetach
-
show:onHiddenChanged(boolean hidden) hidden为false
-
hide:onHiddenChanged(boolean hidden) hidden为true
-
replace:旧Fragment的remove生命周期->新Fragment的add生命周期
-
replace+addToBackStack:onPause->onStop->onDestroyView->新Fragment的add生命周期
之后点击back:新Fragment的remove->onCreateView->onViewCreated->onActivityCreated->onStart->onResume 就是第一张图的线 -
detach:onPause->onStop->onDestroyView 可以看到只是视图被移除,Fragment关联状态还是不变,还是处于FragmentManger的管理下
-
FragmentTransaction.attach(Fragment var1):onStart->onResume->onCreateView
注意:Fragment的show和hide仅仅是将Fragment视图设置为是否可见,不会调用任何生命周期。该Fragment的生命周期还是会随着Activity的生命周期变化而变化,例如FragmentA hide、FragmentB show,点击Home A和B都会onPause->onStop
应用被系统回收对生命周期的影响
-
单独一个Fragment
onDestroyView->onDestroy->onDetach->add生命周期 -
Fragment A hide,Fragment B show
A.onDestroyView->A.onDestroy->A.onDetach->B.onDestroyView->B.onDestroy->B.onDetach->A.onAttach->A.onCreate->B.onAttach->B.onCreate->A.onCreateView->A.onActivityCreated->B.onCreateView->B.onActivityCreated->A.onStart->B.onStart->A.onResume->B.onResume
ViewPager对生命周期的影响
ViewPager为了防止滑动出现卡顿,有一个缓存机制,默认情况下ViewPager会创建并缓存当前页面左右两边的页面(如Fragment)。左右两个Fragment都会执行从onAttach->….->onResume的生命周期,此时Fragment的生命周期已经不可靠。不过在Fragment切换的时候会调用setUserVisibleHint(boolean isVisibleToUser),isVisibleToUser表示是否对用户可见。因此可以在setUserVisibleHint进行Fragment是否可见的判断。
懒加载
1.ViewPager嵌套Fragment
判断setUserVisibleHint 为true 对用户可见 才尝试加载数据
要注意Fragment再嵌套 Viewpager,需要判断父Fragment是否可见
2. add hide show 方式
通过onHiddenChanged 为false时 对用户可见,尝试加载数据