关键点
FragmentStateAdapter是继承自RecyclerView.Adapter,ViewPage2是基于RecyclerView进行实现的。FragmentStateAdapter在实例化的时候,会持有一个Lifecycle对象,而该Lifecycle对象从Fragment或者Activity得来。
源码解析
FragmentStateAdapter{
...
//该方法是RecyclerView.Adapter的回调,在RecyclerView调用setAdapter时进入
@CallSuper
@Override
public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
checkArgument(mFragmentMaxLifecycleEnforcer == null);
mFragmentMaxLifecycleEnforcer = new FragmentMaxLifecycleEnforcer();
mFragmentMaxLifecycleEnforcer.register(recyclerView);
}
//该方法是RecyclerView.Adapter的回调,在RecyclerView首次调用setAdapter时不进入,之后每次调用setAdapter都进入
@CallSuper
@Override
public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
mFragmentMaxLifecycleEnforcer.unregister(recyclerView);
mFragmentMaxLifecycleEnforcer = null;
}
//内部类