生命周期
-
单看 frg 自己的生命周期有以下几个相关方法,按从上往下执行
- onAttach
- onCreate
- onCreateView
- onViewCreated
- onActivityCreated:表示 activiy create 流程结束,所以在
Activity#onStart 中回调 - onStart
- onResume
- onPause
- onStop
- onDestroyView
- onDestroy
- onDetach
-
frg 与 act 联用时,因为
activity 会在生命周期方法(除 onResume)里回调 fragment 的生命周期方法,所以 Frg 生命周期调用都晚于 Activity 相应的生命周期。如果在自己的 Activity 中重写生命周期方法,并在 super. 前后加日志,可发现 Fragment 的调用会出现在两者之间 -
frg#onResume 并不是在 activity#onResume() 中调用,但
activity#onResume 先调用,fragment#onResume() 后调用。在 Activity#performResume() 中可看到两者调用逻辑final void performResume(boolean followedByPause, String reason) { // 调用 Application.ActivityLifecycleCallbacks#onActivityPreResumed dispatchActivityPreResumed(); // 调用 Activity#onRestart() performRestart(true /* start */, reason); mCalled = false; // Activity#onResume mInstrumentation.callActivityOnResume(this); mCalled = false; mFragments.dispatchResume(); mFragments.execPendingActions(); // 这里才真正调用到 frg#onResume onPostResume(); // Application.ActivityLifecycleCallbacks#onPostResume() dispatchActivityPostResumed(); Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER); }
通过 fragmentManager#add
此时 frg 的处理在 Activity#onStart() 中触发,所以相应方法为:
activity#onCreate, activity#onStart,frg 直到 onStart,activity#onResume,frg#onResume
通过 viewpager
fragment 的初始化时机在 ViewPager#onMeasure() 中,因此整个生命周期与使用 fragmentManager#add 有所区别。我们知道,
view 的三大流程在 onResume() 以后,最终到 ViewRootImpl#setView() 中注册同步信号监听,待信号到来后 post 一个 msg 到主 MessageQueue 中,然后才开始三大流程。因此,此时生命周期调用如下:Activity onCreate,onStart, onResume,frg 的生命周期直到 onResume
xml 中 fragment 标签
xml 的解析肯定从 setContentView() 开始,所以:
activity#onCreate 一定先执行,里面调用了 setContentView(),由 LayoutInflater 解析 <fragment> 标签- 然后
fragment 执行到 onViewCreated。因为这里 Activity#onCreate() 并没有执行完成,所以不会执行 Fragment#onActivityCreated() - 再执行
Activity#onStart(),fragment#onActivityCreated, fragment#onStart() - 随后正常流程
这里面注意是 Fragment#onActivityCreated() 流程比较特殊,主要是因为它由 Activity#onStart() 调起。