天天看点

Activity与Fragment的生命周期测试

一个Activity中放入2个Fragment,然后测试Activity和2个Fragment的生命周期

注解:

1、主Activity onCreate后才开始依次初始化每个Fragment,每个Fragment先onAttach,然后onCreate,onCreateView,onViewCreated,这里值得注意的是,与Activity不同,Fragment的onCreate中,并没有创建、呈现子组件,所以在onCreate中,是无法访问子组件的。在onCreateView运行完成后,Fragment中才创建添加了子组件。所以至少要再onViewCreated中,才能用 fragment.getView().findViewById(R.id.xxx)获取子组件的引用。

2、主Activity中所有Fragment依次执行完onViewCreated之后,Activity才onStart开始显示界面。这时每个Fragment会调用onActivityCreated,仅仅在Activity初次onStart时,每个Fragment才会调用onActivityCreated,Activity以后再次调用onStart,Fragment不会再调用onActivityCreated(根据onActivityCreated的名称,这是可想而知的)。如果某个Fragment中的组件想访问其他Fragment中组件的数据,那么必须等到该Fragment调用onActivityCreated时,才能保证其他所有Fragment都已创建了子组件,在onActivityCreated之前,很可能会因为别的Fragment还没有初始化创建子组件而导致findViewById返回null。每个Fragment执行onActivityCreated后,会执行onStart。

3、主Activity分别执行onResume,onPause,onStop之后,每个Fragment也会跟着Activity之后依次执行同名的方法,即Activity.onResume——>Fragment1.onResume——>Fragment2.onResume……。但Fragment没有onRestart方法,主Activity重新回到栈顶显示界面,执行onRestart,onStart,每个Fragment依次执行onStart(没有onRestart)

4、主Activity退出时,Activity和每个Fragment依次执行onPause,onStop。最后主Activity调用onDestroy。每个Fragment依次调用onDestroyView,onDestroy,onDetach,注意Fragment最后的回调方法是onDetach而不是onDestroy