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時 對用戶可見,嘗試加載數據