RecyclerView IndexOutOfBoundsException 问题

在项目中遇到一个RecyclerView 偶现的奔溃,查看日志,发现是:
java.lang.IndexOutOfBoundsException: Index: 39, Size: 39
at java.util.LinkedList.checkElementIndex(LinkedList.java:555)
at java.util.LinkedList.get(LinkedList.java:476)
at android.support.v7.widget.RecyclerView.dispatchOnScrolled(RecyclerView.java:4844)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep3(RecyclerView.java:3909)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3540)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:4082)
at android.view.View.layout(View.java:19781)
at android.view.ViewGroup.layout(ViewGroup.java:6144)
at android.support.v4.widget.SwipeRefreshLayout.onLayout(SwipeRefreshLayout.java:606)
at android.view.View.layout(View.java:19781)
at android.view.ViewGroup.layout(ViewGroup.java:6144)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:19781)
at android.view.ViewGroup.layout(ViewGroup.java:6144)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1816)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1660)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1569)
at android.view.View.layout(View.java:19781)

猜测原因是,RecyclerView的对于的数据被更改,比如,RecyclerView 当前的List 的size是39,然后,把这个List 删除了一部分,这个操作没有及时调用RecyclerView的notify造成了。
由于项目这个List修改的地方很多,很底层,目前使用临时的解决方案(网上其他方案都无法彻底catch这个异常,有这个烦恼的,请查看下面的代码),对异常进行try-catch 处理,具体代码如下:

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

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

    public LinearLayoutMgr(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 (Exception e) {
            e.printStackTrace();
            LogUtil.d("catch exception");
        }
    }

    @Override
    public void scrollToPosition(int position) {
        try {
            super.scrollToPosition(position);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.d("catch exception");
        }
    }
}

在初始化RecyclerView 的时候,使用这个LinearLayoutMgr 代替系统的LinearLayoutManager即可

原文地址:https://www.cnblogs.com/bylijian/p/10372905.html