首先回顾一下Activity的生命周期
Fragment生命周期
官方解释
Lifecycle
Though a Fragment’s lifecycle is tied to its owning activity, it has its own wrinkle on the standard activity lifecycle. It includes basic activity lifecycle methods such as onResume(), but also important are methods related to interactions with the activity and UI generation.
The core series of lifecycle methods that are called to bring a fragment up to resumed state (interacting with the user) are:
1 onAttach(Activity) called once the fragment is associated with its activity.
2 onCreate(Bundle) called to do initial creation of the fragment.
3 onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.
4 onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.onCreate().
5 onViewStateRestored(Bundle) tells the fragment that all of the saved state of its view hierarchy has been restored.
6 onStart() makes the fragment visible to the user (based on its containing activity being started).
7 onResume() makes the fragment interacting with the user (based on its containing activity being resumed).
As a fragment is no longer being used, it goes through a reverse series of callbacks:
1 onPause() fragment is no longer interacting with the user either because its activity is being paused or a fragment operation is modifying it in the activity.
2 onStop() fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity.
3onDestroyView() allows the fragment to clean up resources associated with its View.
4 onDestroy() called to do final cleanup of the fragment’s state.
5 onDetach() called immediately prior to the fragment no longer being associated with its activity.
对比
体验Fragment生命周期的变化
切换到Fragment
onAttach
onCreate
onCreateView
onActivityCreated
onStart
onResume
屏幕灭掉:
onPause
onSaveInstanceState
onStop
屏幕解锁
onStart
onResume
切换到其他Fragment:
onPause
onStop
onDestroyView
切换回本身的Fragment:
onCreateView
onActivityCreated
onStart
onResume
回到桌面
onPause
onSaveInstanceState
onStop
回到应用
onStart
onResume
退出应用
onPause
onStop
onDestroyView
onDestroy
onDetach