美文网首页
RecyclerView Inconsistency detec

RecyclerView Inconsistency detec

作者: 逃离_102 | 来源:发表于2022-08-10 17:41 被阅读0次

    问题

    RecyclerView 报:java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionCommonRecyclerViewHolder{d62c78b position=14 id=-1, oldPos=-1, pLpos:-1 no parent}

    问题分析

    RecyclerView 数据发送变化时,刷新时导致的问题。网络总结可能有几种情况:
    1,数据修改跟view刷新不在同一个线程,导致问题;
    2,数据修改了,没有notify RecyclerView;
    3,notifyItemRangeInserted,notifyItemRangeRemoved,itemCount对应识别有问题;
    4,LayoutManager中onLayoutChildren,scrollVerticallyBy,scrollHorizontallyBy, RecyclerView view的原生bug。

    解决方法

    1,确保数据改变时马上notify RecyclerView,并在统一线程;
    2,替换notifyItemRangeInserted,notifyItemRangeRemoved,直接用notifyDataSetChanged;
    3,try catch LayoutManager 中的onLayoutChildren,scrollVerticallyBy,scrollHorizontallyBy方法,代码如下:

        @Override
        public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
            try {
                super.onLayoutChildren(recycler, state);
            } catch (IndexOutOfBoundsException | NullPointerException e) {
                e.printStackTrace();
            }
        }
    
        @Override
        public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
            try {
                return super.scrollVerticallyBy(dy, recycler, state);
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
            return 0;
        }
    
        @Override
        public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
            try {
                return super.scrollHorizontallyBy(dx, recycler, state);
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
            return 0;
        }
    

    总结

    目前我这边遇到的是偶现问题,把所有这些都用上了,希望能解决。遇到这种问题感觉还是要用全套。

    就说到这了,有什么不对的地方,欢迎指正,有什么没说全的,欢迎讨论留言

    相关文章

      网友评论

          本文标题:RecyclerView Inconsistency detec

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