前言
之前文章中介绍了RecycledViewPool,但是在项目中不可能那么简单调用,我们不应该用静态变量或者单例来创建那个共享的ViewPool
实现
比较好的实现是使用ViewModel,让多个Fragment公用同一个ViewModel对象
public class SharedViewPoolViewModel extends ViewModel {
//for MainContentFragment
private RecyclerView.RecycledViewPool mainContentFragmentPool;
public RecyclerView.RecycledViewPool getMainContentFragmentPool() {
if (mainContentFragmentPool == null)
mainContentFragmentPool = new RecyclerView.RecycledViewPool();
return mainContentFragmentPool;
}
}
- 如果是Activity中包含多个Fragment
SharedViewPoolViewModel sharedViewPoolModel = ViewModelProviders.of(getActivity()).get(SharedViewPoolViewModel.class);
recyclerView.setRecycledViewPool(sharedViewPoolModel.getHomeOutdoorPool());
- 如果是Fragment中包含多个Fragment
SharedViewPoolViewModel sharedViewPoolModel = ViewModelProviders.of(null == getParentFragment() ? this : getParentFragment()).get(SharedViewPoolViewModel.class);
recyclerView.setRecycledViewPool(sharedViewPoolModel.getHomeOutdoorPool());
参考
Reduce the number of inflation of ViewHolders drastically by sharing a ViewPool across multiple…