RecycledViewPool项目中使用

2018-10-30  本文已影响0人  tesla1984

前言

之前文章中介绍了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;
    }
}

SharedViewPoolViewModel sharedViewPoolModel = ViewModelProviders.of(getActivity()).get(SharedViewPoolViewModel.class);
recyclerView.setRecycledViewPool(sharedViewPoolModel.getHomeOutdoorPool());

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…

上一篇 下一篇

猜你喜欢

热点阅读