Lifecycle与Activity Fragment绑定原理
Lifecycle组件
Lifecycle组件是基于观察者模式实现的跟踪并回调其宿主生命周期状态的组件
Lifecycle具体实现类是LifecycleRegistry
Lifecycle基于状态和事件的变化过程实现触发观察者具体方法
(每个观察者注册时也会有其状态,初始是initialized状态,当lifecycle调用handleLifecycleEvent方法时,lifecycle的状态会变成经过该事件后的状态。
状态是点,事件是线,通过某事件,lifecycle的状态就能进行状态改变,从而调用sync方法同步观察者的状态,而观察者从当前状态转变为另一状态也将触发一系列事件回调)
Lifecycle与Activity的绑定
Lifecycle与FragmentActivity的绑定
protected void onCreate(@Nullable Bundle savedInstanceState) {
...其他代码...
super.onCreate(savedInstanceState);
// 通过在Activity生命周期方法中调用触发事件的方法,通知Lifecycle的观察者
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
mFragments.dispatchCreate();
}
Lifecycle与ComponentActivity的绑定
ComponentActivity是FragmentActivity的父类,当不使用FragmentActivity的情况下,想用Lifecycle组件,ComponentActivity将助你一臂之力。
ComponentActivity采用ReportFragment托管其生命周期组件
ComponentActivity
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
// 与ReportFragment组件绑定
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
=======================================================================================================
ReportFragment
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
// 注册Activity生命周期回调的方式绑定Lifecycle
activity.registerActivityLifecycleCallbacks(
new LifecycleCallbacks());
}
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
// 绑定ReportFragment 通过在ReportFragment的生命周期方法中
// 调用Activity的Lifecycle组件的 handleLifecycleEvent() 方法
// 实现Activity与Lifecycle组件的绑定
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
// Hopefully, we are the first to make a transaction.
// 立即执行修改
manager.executePendingTransactions();
}
}
本文地址:https://blog.csdn.net/u013142672/article/details/107942024
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!
网友评论