工作中遇到RecyclerView IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter的bug,查阅了stackoverflow 和git的上的资料,说是recyclerview的bug,在此记录一下解决方案.
1.自定义一个LinearLayoutManager的包装类,在onLayoutChildren()方法里捕获IndexOutOfBoundsException这个异常.
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
2.在进行数据移除和数据增加时,要保证Recyclerview的Adapter中的数据集(假设叫内部数据集)和移除或添加操作后的数据集(假设叫外部数据集)保持一致.
外部数据集同步到内部数据集使用如下方法:
notifyItemRangeRemoved()
notifyItemRangeInserted()
notifyItemRangeChanged()
notifyDataSetChanged() 注:没有默认的动画效果,且不是局部更新
3.使用notifyDataSetChanged同步内部数据集和外部数据集,该方法简单,但是不推荐使用,因为没有默认的动画效果,且不是局部更新
我个人觉得自定义一个LinearLayoutManager类有点重,然后采用第二种方法,查找自己的代码里面有可能使内外部数据集不一致的地方,定位到调用notifyItemInsert(int pos)时必现这个bug,修改notifyItemInsert(int pos)为notifyItemRangeInserted(int positionStart, int itemCount)后问题修复.
如果第二种方法无法解决,可以尝试1,3两种方法.