IndexOutOfBoundsException: Inconsistency detected. Invalid item position 2Inconsistency detected....

最近交接了一个旧项目,项目里面还用的android.surpport系列依赖 

然后在运行中经常会莫名遇到recycleView 数组越界的问题:

java.lang.IndexOutOfBoundsException: Inconsistency detected nvalid item position 2Inconsistency detected. Invalid item position 2(offset:4).state:3

经查询 找到了原因和解决方案,这里参考csdn一位大佬的办法, 链接如下:

https://blog.csdn.net/juhua2012/article/details/80002815


RecyclerView 存在的一个明显的 bug 一直没有修复:

java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position…

重现的方法是:使用 RecyclerView 加官方下拉刷新的时候,如果绑定的 List 对象在更新数据之前进行了 clear,而这时用户紧接着迅速上滑 RV,就会造成崩溃,而且异常不会报到你的代码上,属于RV内部错误。初次猜测是,当你 clear 了 list 之后,这时迅速上滑,而新数据还没到来,导致 RV 要更新加载下面的 Item 时候,找不到数据源了,造成 crash.

在网上看到的解决方法有两个:

1.

就是在刷新,Recyclerview  clear的同时让Recyclerview不能滑动,这样的解决办法也是可以的,可以避免错误的发生,但是我总感觉这样的会影响用户的体验,该解决办法的代码如下:

mRecyclerView.setOnTouchListener(

         new View.OnTouchListener() {

             @Override

             public boolean onTouch(View v, MotionEvent event) {

                 if (mIsRefreshing) {

                     return true ;

                 }  else {

                     return false ;

                 }

             }

         }

);


然后去改变和恢复 mIsRefreshing 这个 boolean 即可。

2.

我们写一个MyLinearLayoutManager去继承LinearLayoutManager,在出现问题的时候我们catch了,这样的处理方法我觉得还是可以的,具体实现如下:

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(); 

        } 

    }  }


其中是重写了onLayoutChildren方法

然后设置Recyclerview的Manager为我们自己的Manager:

mRecyclerView.setLayoutManager(new MyLinearLayoutManager(this));


在这里我用的是第二种方法 ,顺利解决了该问题

你可能感兴趣的:(IndexOutOfBoundsException: Inconsistency detected. Invalid item position 2Inconsistency detected....)