Fragment必須是依存于Activity而存在的,因此Activity的生命周期會(huì)直接影響到Fragment的生命周期。官網(wǎng)這張圖很好的說明了倆者的關(guān)系:

可以看到Fragment比Activity多了幾個(gè)額外的生命周期回調(diào)函數(shù):
onAttach(Activity); //當(dāng)Activity與Fragment發(fā)生關(guān)聯(lián)時(shí)調(diào)用onCreateView(LayoutInflater,ViewGroup,Bundle); //創(chuàng)建該Fragment的視圖onActivityCreate(bundle); //當(dāng)Activity的onCreate();方法返回時(shí)調(diào)用onDestoryView(); //與onCreateView相對應(yīng),當(dāng)改Fragment被移除時(shí)調(diào)用onDetach(); //與onAttach()相對應(yīng),當(dāng)Fragment與Activity的關(guān)聯(lián)被取消時(shí)調(diào)用
注意:除了onCreateView,其他的所有方法如果你重寫了,必須調(diào)用父類對于該方法的實(shí)現(xiàn)。
場景演示 :
切換到該Fragment
11-29 14:26:35.095: D/AppListFragment(7649): onAttach11-29 14:26:35.095: D/AppListFragment(7649): onCreate11-29 14:26:35.095: D/AppListFragment(7649): onCreateView11-29 14:26:35.100: D/AppListFragment(7649): onActivityCreated11-29 14:26:35.120: D/AppListFragment(7649): onStart11-29 14:26:35.120: D/AppListFragment(7649): onResume
屏幕滅掉:
11-29 14:27:35.185: D/AppListFragment(7649): onPause11-29 14:27:35.205: D/AppListFragment(7649): onSaveInstanceState11-29 14:27:35.205: D/AppListFragment(7649): onStop
屏幕解鎖
11-29 14:33:13.240: D/AppListFragment(7649): onStart11-29 14:33:13.275: D/AppListFragment(7649): onResume
切換到其他Fragment:
11-29 14:33:33.655: D/AppListFragment(7649): onPause11-29 14:33:33.655: D/AppListFragment(7649): onStop11-29 14:33:33.660: D/AppListFragment(7649): onDestroyView
切換回本身的Fragment:
11-29 14:33:55.820: D/AppListFragment(7649): onCreateView11-29 14:33:55.825: D/AppListFragment(7649): onActivityCreated11-29 14:33:55.825: D/AppListFragment(7649): onStart11-29 14:33:55.825: D/AppListFragment(7649): onResume
回到桌面
11-29 14:34:26.590: D/AppListFragment(7649): onPause11-29 14:34:26.880: D/AppListFragment(7649): onSaveInstanceState11-29 14:34:26.880: D/AppListFragment(7649): onStop
回到應(yīng)用
11-29 14:36:51.940: D/AppListFragment(7649): onStart11-29 14:36:51.940: D/AppListFragment(7649): onResume
退出應(yīng)用
11-29 14:37:03.020: D/AppListFragment(7649): onPause11-29 14:37:03.155: D/AppListFragment(7649): onStop11-29 14:37:03.155: D/AppListFragment(7649): onDestroyView11-29 14:37:03.165: D/AppListFragment(7649): onDestroy11-29 14:37:03.165: D/AppListFragment(7649): onDetach
比Activity多了一些生命周期,完整和Activity對接上,大家好好利用。
新聞熱點(diǎn)
疑難解答
圖片精選