问题
RecyclerView 报:java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionCommonRecyclerViewHolder{d62c78b position=14 id=-1, oldPos=-1, pLpos:-1 no parent}
问题分析
RecyclerView 数据发送变化时,刷新时导致的问题。网络总结可能有几种情况:
1,数据修改跟view刷新不在同一个线程,导致问题;
2,数据修改了,没有notify RecyclerView;
3,notifyItemRangeInserted,notifyItemRangeRemoved,itemCount对应识别有问题;
4,LayoutManager中onLayoutChildren,scrollVerticallyBy,scrollHorizontallyBy, RecyclerView view的原生bug。
解决方法
1,确保数据改变时马上notify RecyclerView,并在统一线程;
2,替换notifyItemRangeInserted,notifyItemRangeRemoved,直接用notifyDataSetChanged;
3,try catch LayoutManager 中的onLayoutChildren,scrollVerticallyBy,scrollHorizontallyBy方法,代码如下:
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException | NullPointerException e) {
e.printStackTrace();
}
}
@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
return super.scrollVerticallyBy(dy, recycler, state);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
return super.scrollHorizontallyBy(dx, recycler, state);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
return 0;
}
总结
目前我这边遇到的是偶现问题,把所有这些都用上了,希望能解决。遇到这种问题感觉还是要用全套。
网友评论