在使用RecyclerView时,有时候出现类似下方的这种错误:
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 0(offset:0).state:60 android.support.v7.widget.RecyclerView{1dee303 VFED..... .F......
0,0-1440,1952 #7f09025f app:id/rv_account_fund_details}, adapter:com.desjf.dsjr.adapter.bankAdapter.BankFundDetailsItemAdapter@c63c280, layout:com.desjf.dsjr.widget.RecyclerViewNoBugLinearLayoutManager@abd00b9,
context:com.desjf.dsjr.activity.bankActivity.BankAccountFundDetailsActivity@90eccbe
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5628)
at android.support.v7.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:285)
at android.support.v7.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:342)
at android.support.v7.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:358)
at android.support.v7.widget.GapWorker.prefetch(GapWorker.java:365)
at android.support.v7.widget.GapWorker.run(GapWorker.java:396)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
刚开始遇见你会很奇怪,这种错误不会提示你任何一行代码有问题,但它就是会让程序crash掉,使用 RecyclerView 加SwipeRefreshLayout下拉刷新的时候,如果绑定的 List 对象在更新数据之前进行了 clear,而这时用户紧接着迅速上滑 RecyclerView,就会造成崩溃,而且异常不会报到我们的代码上,属于RecyclerView内部错误。这就是当 clear 了 list 之后,这时迅速上滑,此时新数据还没到来,就会导致 RecyclerView 要更新加载下面的 Item 时候,找不到数据源了,造成 crash。这种方法该如何解决,我们可以使用自定义的布局,然后将其加载到RecyclerView 中,手动去捕获这个异常信息,从而不让程序crash,
public class RecyclerViewNoBugLinearLayoutManagerextends LinearLayoutManager {
public RecyclerViewNoBugLinearLayoutManager(Context context) {
super(context);
}
public RecyclerViewNoBugLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super( context, orientation, reverseLayout );
}
public RecyclerViewNoBugLinearLayoutManager(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 catch一下
super.onLayoutChildren( recycler, state );
}catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
@Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
return super.scrollVerticallyBy(dy, recycler, state);
}catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}