美文网首页
RecycledViewPool项目中使用

RecycledViewPool项目中使用

作者: tesla1984 | 来源:发表于2018-10-30 16:52 被阅读0次

前言

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

相关文章

网友评论

      本文标题:RecycledViewPool项目中使用

      本文链接:https://www.haomeiwen.com/subject/htogtqtx.html