Fragment生命週期圖解,fragment和activity生命週期對比android
生命週期變化 : 切換到該Fragmentxml
05-21 14:26:35.095: D/FragmentDemo(7649): onAttach
05-21 14:26:35.095: D/FragmentDemo(7649): onCreate
05-21 14:26:35.095: D/FragmentDemo(7649): onCreateView
05-21 14:26:35.100: D/FragmentDemo(7649): onActivityCreated
05-21 14:26:35.120: D/FragmentDemo(7649): onStart
05-21 14:26:35.120: D/FragmentDemo(7649): onResume
屏幕滅掉:
05-21 14:27:35.185: D/FragmentDemo(7649): onPause
05-21 14:27:35.205: D/FragmentDemo(7649): onSaveInstanceState
05-21 14:27:35.205: D/FragmentDemo(7649): onStop
屏幕解鎖
05-21 14:33:13.240: D/FragmentDemo(7649): onStart
05-21 14:33:13.275: D/FragmentDemo(7649): onResume
切換到其餘Fragment:
05-21 14:33:33.655: D/FragmentDemo(7649): onPause
05-21 14:33:33.655: D/FragmentDemo(7649): onStop
05-21 14:33:33.660: D/FragmentDemo(7649): onDestroyView
切換回自己的Fragment:
05-21 14:33:55.820: D/FragmentDemo(7649): onCreateView
05-21 14:33:55.825: D/FragmentDemo(7649): onActivityCreated
05-21 14:33:55.825: D/FragmentDemo(7649): onStart
05-21 14:33:55.825: D/FragmentDemo(7649): onResume
回到桌面
05-21 14:34:26.590: D/FragmentDemo(7649): onPause
05-21 14:34:26.880: D/FragmentDemo(7649): onSaveInstanceState
05-21 14:34:26.880: D/FragmentDemo(7649): onStop
回到應用
05-21 14:36:51.940: D/FragmentDemo(7649): onStart
05-21 14:36:51.940: D/FragmentDemo(7649): onResume
退出應用
05-21 14:37:03.020: D/FragmentDemo(7649): onPause
05-21 14:37:03.155: D/FragmentDemo(7649): onStop
05-21 14:37:03.155: D/FragmentDemo(7649): onDestroyView
05-21 14:37:03.165: D/FragmentDemo(7649): onDestroyblog
05-21 14:37:03.165: D/FragmentDemo(7649): onDetach生命週期
新建一個Activity,在各個生命週期中輸出log
一、按crtl+f12切換成橫屏時
onSaveInstanceState-->
onPause-->
onStop-->
onDestroy-->
onCreate-->
onStart-->
onRestoreInstanceState-->
onResume-->
二、再按crtl+f12切換成豎屏時,發現打印了兩次相同的log
onSaveInstanceState-->
onPause-->
onStop-->
onDestroy-->
onCreate-->
onStart-->
onRestoreInstanceState-->
onResume-->
onSaveInstanceState-->
onPause-->
onStop-->
onDestroy-->
onCreate-->
onStart-->
onRestoreInstanceState-->
onResume-->
三、修改AndroidManifest.xml,把該Activity添加 Android:configChanges="orientation",執行步驟2,橫屏切換爲豎屏
onSaveInstanceState-->
onPause-->
onStop-->
onDestroy-->
onCreate-->
onStart-->
onRestoreInstanceState-->
onResume-->
四、再執行步驟2,豎屏切換爲橫屏,發現不會再打印相同信息,但多打印了一行onConfigChanged
onSaveInstanceState-->
onPause-->
onStop-->
onDestroy-->
onCreate-->
onStart-->
onRestoreInstanceState-->
onResume-->
onConfigurationChanged-->
五、把步驟3的android:configChanges="orientation" 改爲 android:configChanges="orientation|keyboardHidden",執行步驟2,豎屏切換橫屏,就只打印onConfigChanged
onConfigurationChanged-->
八、再次執行步驟2,橫屏切換回豎屏
onConfigurationChanged-->
總結:
一、不設置Activity的android:configChanges時,切屏會從新調用各個生命週期,切橫屏時會執行一次,切豎屏時會執行兩次
二、設置Activity的android:configChanges="orientation"時,切屏仍是會從新調用各個生命週期,切橫、豎屏時只會執行一次
it
三、設置Activity的android:configChanges="orientation|keyboardHidden"時,切屏不會從新調用各個生命週期,只會執行onConfigurationChanged方法io