IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder

java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder异常处理

一般报这种错误有两种情况:

第一种:list数据源发生变化没有及时刷新adapter,也就是没有及时notifyDataSetChanged()

第二种:以下情况的recycleView偶现错误,以下是第二种错误的解决方案

java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{35b7b5f position=12 id=-1, oldPos=-1, pLpos:-1 no parent}
    at android.support.v7.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition(RecyclerView.java:5251)
    at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5433)
    at android.support.v7.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:270)
    at android.support.v7.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:324)
    at android.support.v7.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:337)
    at android.support.v7.widget.GapWorker.prefetch(GapWorker.java:344)
    at android.support.v7.widget.GapWorker.run(GapWorker.java:370)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:185)
    at android.app.ActivityThread.main(ActivityThread.java:6493)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:916)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:806)

具体也没有报哪一行出错,最终还是要google大神去修复

临时解决方案:
创建一个LinearLayoutManagerWrapper继承LinearLayoutManager,重写onLayoutChildren方法,加个异常处理就行了

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

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

    public WrapContentLinearLayoutManager(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();  
        }  
    }  
}  

然后recycleView中设置这个布局就可以了,其他布局样式类似

mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); 

你可能感兴趣的:(android)