Android中IndexOutOfBoundsException: Inconsistency detected. Invalid item position 1(offset:1).state:4

RecyclerView中的bug

  在写一个本地文件搜索功能,搜索到一定数量就回掉一次结果给RecyclerView去重新刷新数据(描述:刷新前clear掉旧数据,设置新数据,在notifyDataSetChanged…),这时遇到了下面一个问题

这里写图片描述

  一看数组越界异常,迅速检查下自己代码,没有问题,多运行几次,还是数组越界异常,但是描述每次都会不同

这里写图片描述

  嗯,怎么看都绝对不是自己代码问题了,直接搜搜,居然是recycleview自己存在的bug,还那么多人遇到,这里出现这样的bug是notifyDataSetChanged前后数据不一致的问题,具体怎么不一致这里就不说了,这里采用解决办法如下:

public class MyLinearLayoutManager extends LinearLayoutManager {
    public MyLinearLayoutManager(Context context) {
        super( context );
    }

    public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super( context, orientation, reverseLayout );
    }

    public MyLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super( context, attrs, defStyleAttr, defStyleRes );
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        try {
            //这里捕获之前的数组越界问题...
            super.onLayoutChildren( recycler, state );
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        }

    }
}

参考资料:走你

猜你喜欢

转载自blog.csdn.net/u014769864/article/details/79129654
今日推荐