1. 程式人生 > >Fragment(1)-生命週期方法與Fragment檢視是否可見間的細節

Fragment(1)-生命週期方法與Fragment檢視是否可見間的細節

前言

根據ViewPager+Frgment的小例子,來研究Fragment生命週期方法與Fragment檢視是否可見間的細節。

正文

所用資源:ViewPager+Fragment,ViewPager只預設預載入1頁,共三個Fragment。

動作1:執行App,介面顯示

//PlaceholderFragment: 1 setUserVisibleHint() called with: isVisibleToUser = [false]
//PlaceholderFragment: 2 setUserVisibleHint() called with: isVisibleToUser = [false]
//PlaceholderFragment: 1 onAttach() called with: //PlaceholderFragment: 1 onCreate() called with: //PlaceholderFragment: 1 setUserVisibleHint() called with: isVisibleToUser = [true] //PlaceholderFragment: 1 onCreateView() called with: //PlaceholderFragment: 1 onViewCreated() called with: //PlaceholderFragment: 1 onActivityCreated() called with:
//PlaceholderFragment: 1 onStart() called with: //PlaceholderFragment: 1 onResume() called with: //PlaceholderFragment: 2 onAttach() called with: //PlaceholderFragment: 2 onCreate() called with: //PlaceholderFragment: 2 onCreateView() called with: //PlaceholderFragment: 2 onViewCreated() called with: //PlaceholderFragment: 2 onActivityCreated() called with:
//PlaceholderFragment: 2 onStart() called with: //PlaceholderFragment: 2 onResume() called with:

首先,會呼叫前兩頁的setUserVisibleHint()方法並設定為false,表明兩個Fragmnet所代表的檢視,還尚未顯示。

接著執行Fragment1的生命週期流程,並在onCreate()與onCreateView()之間執行setUserVisbleHint()為true,來表示Fragment1已使用者可見。

隨後執行Fragment2的生命週期流程,直至onResume()被呼叫。但是此時Fragment2還處於使用者不可見狀態。

動作2:滑動到第二個Fragment

//PlaceholderFragment: 3 setUserVisibleHint() called with: isVisibleToUser = [false]
//PlaceholderFragment: 1 setUserVisibleHint() called with: isVisibleToUser = [false]
//PlaceholderFragment: 2 setUserVisibleHint() called with: isVisibleToUser = [true]
//PlaceholderFragment: 3 onAttach() called with:
//PlaceholderFragment: 3 onCreate() called with:
//PlaceholderFragment: 3 onCreateView() called with:
//PlaceholderFragment: 3 onViewCreated() called with:
//PlaceholderFragment: 3 onActivityCreated() called with:
//PlaceholderFragment: 3 onStart() called with:
//PlaceholderFragment: 3 onResume() called with:

首先,執行3個Fragment的setUserVisbleHint()方法,去表明Fragment是否為可見狀態。此時,Fragment2處於可見狀態,Fragment1和預載入的Fragment3處於不可見狀態。

緊接著再去執行Fragment3的生命週期方法。

動作3:滑動到第三個Fragment

//PlaceholderFragment: 2 setUserVisibleHint() called with: isVisibleToUser = [false]
//PlaceholderFragment: 3 setUserVisibleHint() called with: isVisibleToUser = [true]
//PlaceholderFragment: 1 onPause() called with:
//PlaceholderFragment: 1 onStop() called with:
//PlaceholderFragment: 1 onDestroyView() called with:

首先,先執行當前Fragment和快取Fragmnet2的setUserVisibleHint()方法,表明各自的可見狀態,此時,Fragment3處於可見狀態。

緊接著去釋放Fragment1的檢視資源,但並不銷燬Fragment1

結論

Fragment和Activity的大部分生命週期繫結在一起,但是Fragment的onResume()並不意味著Fragment對於使用者可見,真正Fragment對使用者可見會執行的方法是setUserVisbleHInt()並且為true時。

在Fragment的宣告週期中,setUserVisbleHint()方法會被呼叫兩次,第一次是在Fragment宣告週期尚未開始時,用於初始化userVisbleHint變數;第二次實在onCreate()與onCreateView()之間呼叫,表明Fragment已經處於可見狀態。