首頁  >  文章  >  Java  >  Android中Fragment與Activity的生命週期對比

Android中Fragment與Activity的生命週期對比

高洛峰
高洛峰原創
2017-01-07 16:09:161407瀏覽

Fragment必須是依賴Activity而存在的,因此Activity的生命週期會直接影響Fragment的生命週期。官網這張圖很好的說明了倆的關係:

Android中Fragment與Activity的生命週期對比

可以看到Fragment比Activity多了幾個額外的生命週期回調函數:

onAttach(Activity);  //当Activity与Fragment发生关联时调用
 
onCreateView(LayoutInflater,ViewGroup,Bundle);  //创建该Fragment的视图
 
onActivityCreate(bundle);  //当Activity的onCreate();方法返回时调用
 
onDestoryView();  //与onCreateView相对应,当改Fragment被移除时调用
 
onDetach();  //与onAttach()相对应,当Fragment与Activity的关联被取消时调用

注意:除了onCreateView,其他的所有方法如果你重寫了,必須呼叫父類別對於該方法的實作。

場景示範:

切換到該Fragment

11-29 14:26:35.095: D/AppListFragment(7649): onAttach
11-29 14:26:35.095: D/AppListFragment(7649): onCreate
11-29 14:26:35.095: D/AppListFragment(7649): onCreateView
11-29 14:26:35.100: D/AppListFragment(7649): onActivityCreated
11-29 14:26:35.120: D/AppListFragment(7649): onStart
11-29 14:26:35.120: D/AppListFragment(7649): onResume

螢幕滅掉:

11-29 14:27:35.185: D/AppListFragment(7649): onPause
11-29 14:27:35.205: D/AppListFragment(7649): onSaveInstanceState
11-29 14:27:35.205: D/AppListFragment(7649): onStop

螢幕解鎖

11-29 14:33:13.240: D/AppListFragment(7649): onStart
11-29 14:33:13.275: D/AppListFragment(7649): onResume

   

回到桌面

11-29 14:33:33.655: D/AppListFragment(7649): onPause
11-29 14:33:33.655: D/AppListFragment(7649): onStop
11-29 14:33:33.660: D/AppListFragment(7649): onDestroyView

   

回到應用

11-29 14:33:55.820: D/AppListFragment(7649): onCreateView
11-29 14:33:55.825: D/AppListFragment(7649): onActivityCreated
11-29 14:33:55.825: D/AppListFragment(7649): onStart
11-29 14:33:55.825: D/AppListFragment(7649): onResume

   

退出應用

rrrereee

,大家好好利用。

更多Android中Fragment與Activity的生命週期對比相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn