异常:
java.lang.IndexOutOfBoundsException:
Inconsistency detected. Invalid item position 10(offset:10).state:21
原因:
SwipeRefreshLayout 与RecyclerView滑动产生冲突,导致的崩溃网上很多解决办法,Touch处理,自定义LayoutManager捕获异常,亲测!都不能完美的防止崩溃!有时崩溃在onLayoutChildren中捕获不到,于是,翻阅源码,终于有了解决办法,在onLayoutChildren和scrollVerticallyBy/scrollHorizontallyBy同时捕获,尽可能的捕获异常,完美的防止崩溃的发生
解决:
/**
* Synopsis 解决SwipeRefreshLayout 与RecyclerView滑动产生冲突,导致的崩溃
* java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 12(offset:12).state:21
* Author Mosr
* Version ${VERSION}
* Create 2018.10.31 16:11
* Email intimatestranger@sina.cn
*/
public class CustomLinearLayoutManager extends LinearLayoutManager {
public CustomLinearLayoutManager(Context context) {
super(context);
}
public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public CustomLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 纵向
*
* @param dy
* @param recycler
* @param state
*
* @return
*/
@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
int i = 0;
try {
i = super.scrollVerticallyBy(dy, recycler, state);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
return i;
}
/**
* 横向
*
* @param dx
* @param recycler
* @param state
*
* @return
*/
@Override
public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
int i = 0;
try {
super.scrollHorizontallyBy(dx, recycler, state);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
return i;
}
}
RecyclerView配置:
CustomLinearLayoutManager mLinearLayoutManager = new CustomLinearLayoutManager(this);
mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mLinearLayoutManager);