本文共 1690 字,大约阅读时间需要 5 分钟。
Fragment(Activity同理,我们 本文以Fragment为例,下同):实现了LifecycleOwner接口,这意味着Fragment对象持有生命周期对象(Lifecycle),并可以通过Lifecycle getLifecycle()方法获取内部的Lifecycle对象:
Fragment:LifecycleOwnerSSC采集器修复,需要请搜索【大神源码论坛】客服企娥3393756370 V信17061863513,public class Fragment implements xxx, LifecycleOwner {//...省略其他
LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Overridepublic Lifecycle getLifecycle() { return mLifecycleRegistry;}
}
public interface LifecycleOwner {
可以看到,实现的getLifecycle()方法,实际上返回的是 LifecycleRegistry 对象,LifecycleRegistry对象实际上继承了 Lifecycle,这个下文再讲。
持有Lifecycle有什么作用呢?实际上在Fragment对应的生命周期内,都会发送对应的生命周期事件给内部的 LifecycleRegistry对象处理:
public class Fragment implements xxx, LifecycleOwner {
//...void performCreate(Bundle savedInstanceState) { onCreate(savedInstanceState); //1.先执行生命周期方法//...省略代码//2.生命周期事件分发mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);}void performStart() { onStart(); //... mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);}void performResume() { onResume(); //... mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);}void performPause() { //3.注意,调用顺序变了 mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE); //... onPause();}void performStop() { mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP); //... onStop();}void performDestroy() { mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY); //... onDestroy();}
}
随着Fragment不同走到不同的生命周期,除了暴露给我们的生命周期方法onCreate/onStart/…./onDestroy等,同时,Fragment内部的Lifecycle对象(就是mLifecycleRegistry)还将生命周期对应的事件作为参数传给了 handleLifecycleEvent() 方法。
转载于:https://blog.51cto.com/13974338/2175962