Activity的生命周期方法
Activity一共有以下7个生命周期方法:
onCreate():创建时调用
onStart():可见时调用
onResume():获取焦点时用
onPause():失去焦点时调用
onStop():不可见时调用
onRestart():重启时调用
onDestory():销毁时调用
Fragment的生命周期方法
Fragment拥有和Activity相同的6个生命周期方法,没有onRestart()。除此之外还多了onAttach(),onCreateView(),onActivityCreated(),onDestoryView(),onDetach()这五个。所以Fragment一共有以下11个生命周期方法:
onAttach():和宿主Activity建立关联时调用
onCreate():创建时调用
onCreateView():加载Fragment的布局时调用
onActivityCreated():宿主Activity创建完毕时调用
onStart():可见时调用
onResume():获取焦点时用
onPause():失去焦点时调用
onStop():不可见时调用
onDestoryView():移除Fragment的布局时调用
onDestory():销毁时调用
onDetach():与宿主Activity解除关联时调用
实验
做一个简单的实验,MainActivity分成LeftFragment和RightFragment。LeftFragment有两个按钮,用于打开一个DialogTheme的DialogActivity和SecondActivity。然后在MainActivity,RightFragment,DialogAcitvity和SecondActivity的生命周期方法调用时打印相应的log。
程序启动时
MainActivity: onCreate
RightFragment: onAttach
RightFragment: onCreate
RightFragment: onCreateView
RightFragment: onActivityCreated
MainActivity: onStart
RightFragment: onStart
MainActivity: onResume
RightFragment: onResume
打开DialogActivity时
RightFragment: onPause
MainActivity: onPause
DialogActivity: onCreate
DialogActivity: onStart
DialogActivity: onResume
点返回键返回MainActivity时
DialogActivity: onPause
MainActivity: onResume
RightFragment: onResume
DialogActivity: onStop
DialogActivity: onDestroy
进入SecondActivity时
RightFragment: onPause
MainActivity: onPause
SecondActivity: onCreate
SecondActivity: onStart
SecondActivity: onResume
点击返回键回到MainActivity时
RightFragment: onStop
MainActivity: onStop
SecondActivity: onPause
MainActivity: onRestart
MainActivity: onStart
RightFragment: onStart
MainActivity: onResume
RightFragment: onResume
SecondActivity: onStop
SecondActivity: onDestroy
再次点击返回键退出程序时
RightFragment: onPause
MainActivity: onPause
RightFragment: onStop
MainActivity: onStop
RightFragment: onDestroyView
RightFragment: onDetach
MainActivity: onDestroy
网友评论