The core series of lifecycle methods that are called to bring a fragment up to resumed state (interacting with the user) are:
onAttach(Activity)
called once the fragment is associated with its activity.onCreate(Bundle)
called to do initial creation of the fragment.onCreateView(LayoutInflater, ViewGroup, Bundle)
creates and returns the view hierarchy associated with the fragment.onActivityCreated(Bundle)
tells the fragment that its activity has completed its ownActivity.onCreate()
.onViewStateRestored(Bundle)
tells the fragment that all of the saved state of its view hierarchy has been restored.onStart()
makes the fragment visible to the user (based on its containing activity being started).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:
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.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.onDestroyView()
allows the fragment to clean up resources associated with its View.onDestroy()
called to do final cleanup of the fragment's state.onDetach()
called immediately prior to the fragment no longer being associated with its activity
以上内容摘自google官方api,可以看出fragment的生命周期大致分为2个阶段。
阶段1:to Resume State
(1)onAttach:一旦Fragment与Activity关联建立(Activity中setContentView(R.layout.fragment)(静态)或getFragmentManager().beginTransaction().commit()(动态)),该回调函数被调用。可用于赋值Fragment接口
@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
mFragmentEventListener = (FragmentEventListener)activity
}
(2)onCreate:与Activity的onCreate类似,做一些初始化工作
(3)onCreateView:初始化Fragment的view
(4)onActivityCreate:告诉Fragment,Activity的onCreate函数调用完毕,可用于判断Activity中的一些初始化状态。
(5)onViewStatedRestored:告诉Fragment所有视图的状态都已经恢复完成
(6)onStart:Fragment可见(基于Activity调用onStart)
(7)onResume:Fragment可以与用户交互(基于Activity调用onResume)
阶段2:to Destory State
onDestoryView:允许Fragment清除一些与视图关联的Resource
onDetach:当Fragment与Activity关联解除时立即调用