###写在前面
在使用RecyclerView中出现了一个问题,如下图
###解决办法:
我们在使用RecycxlerView时,通常先回设置一个LayoutManager
我们的问题出现在LayoutManager的onLayoutChildren方法中,我们只要在onLayoutChildren中捕获这个异常即可,下面我以LinearLayoutManager为例。
先写一个类LinearLayoutManagerWrap继承LinearLayoutManager,然后重新onLayoutChildren方法即可,如下代码:
public class LinearLayoutManagerWrap extends LinearLayoutManager {
public LinearLayoutManagerWrap(Context context) {
super(context);
}
public LinearLayoutManagerWrap(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public LinearLayoutManagerWrap(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
// 在这里通过try来捕获这个异常即可
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
}
然后把LinearLayoutManagerWrap设置RecyclerView即可