在onCreateViewHolder和onBindViewHolder中进行实例化时,RecyclerView会花费很多时间:进度栏冻结

sof*_*ply 1 performance android android-recyclerview

我在RecyclerView中填充了250个项目。每个视图只有4个TextView。为RecyclerView创建适配器时,onCreateViewHolder大约需要5毫秒,而onBindViewHolder大约需要3毫秒。对于250个项目,我们将延迟2秒。在这两秒钟内,由于必须在主线程上执行适配器分配,因此UI冻结。

例如,在onCreateViewHolder中,除了布局膨胀以外,没有什么其他操作:

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    long lTime = System.currentTimeMillis();
    switch (viewType) {
        case TYPE_HEADER:
            SpendingHeader lResult = new SpendingHeader(LayoutInflater.from(mContext).inflate(R.layout.layout_spending_item_header, null));
            LogUtils.logTime(lTime, TAG, "onCreateViewHolder");
            return lResult;
        default:
            SpendingItem lResult2 = new SpendingItem(LayoutInflater.from(mContext).inflate(R.layout.layout_spending_item, null));
            LogUtils.logTime(lTime, TAG, "onCreateViewHolder");
            return lResult2;
    }
}
Run Code Online (Sandbox Code Playgroud)

完整的计算工作是在AsyncTask中的后台线程上完成的。只有onCerateViewHolder和onBindViewHolder占用大量时间,以致进度条冻结。我可以等待,但是进度条冻结会不好。有办法避免这种情况吗?另外,我不希望有一个懒惰的列表,例如,滚动到第30个项目后,您会在其中获得进度条。

注意:同样,对于actionbarBar ControllableLayout行为,我的Recyclerview也必须是NestedScrollView的一部分。这可能是个问题吗?看这里

Dim*_*zis 5

您不需要RecyclerView使用NestedScrollViewAppBarLayout即使没有它,它也将正确运行。

滞后的原因是RecyclerView适配器创建ViewHolders并将其绑定到它拥有的所有项目(在您的情况下为250),这是因为NestedScrollView使RecyclerView测量自身的方式错误(以匹配NestedScrollView大小),在这种情况下RecyclerView“认为”它需要创建足够的ViewHolders以适合此错误的大小。

您也可以尝试致电setAutoMeasureEnabled(true)以使其能够正确衡量自己。