Home >Java >javaTutorial >Comparison of the life cycles of Fragment and Activity in Android
Fragment must exist dependent on Activity, so the life cycle of Activity will directly affect the life cycle of Fragment. This picture on the official website illustrates the relationship between the two very well:
# You can see that Fragment has several additional life cycle callback functions than Activity:
onAttach(Activity); //当Activity与Fragment发生关联时调用 onCreateView(LayoutInflater,ViewGroup,Bundle); //创建该Fragment的视图 onActivityCreate(bundle); //当Activity的onCreate();方法返回时调用 onDestoryView(); //与onCreateView相对应,当改Fragment被移除时调用 onDetach(); //与onAttach()相对应,当Fragment与Activity的关联被取消时调用
Note: Except for onCreateView, if you override all other methods, you must call the parent class's implementation of this method.
Scene demonstration:
Switch to this 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
Screen off:
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
Screen unlock
11-29 14:33:13.240: D/AppListFragment(7649): onStart 11-29 14:33:13.275: D/AppListFragment(7649): onResume
Switch to other Fragment :
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
Switch back to your own Fragment:
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
Back to the desktop
11-29 14:34:26.590: D/AppListFragment(7649): onPause 11-29 14:34:26.880: D/AppListFragment(7649): onSaveInstanceState 11-29 14:34:26.880: D/AppListFragment(7649): onStop
##Back to the application
11-29 14:36:51.940: D/AppListFragment(7649): onStart 11-29 14:36:51.940: D/AppListFragment(7649): onResumeExit the application
11-29 14:37:03.020: D/AppListFragment(7649): onPause 11-29 14:37:03.155: D/AppListFragment(7649): onStop 11-29 14:37:03.155: D/AppListFragment(7649): onDestroyView 11-29 14:37:03.165: D/AppListFragment(7649): onDestroy 11-29 14:37:03.165: D/AppListFragment(7649): onDetachIt has more life cycles than Activity, and is completely connected to Activity. Everyone can take advantage of it. For more articles related to the life cycle comparison of Fragment and Activity in Android, please pay attention to the PHP Chinese website!