java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter
RecyclerView 原生问题
Cause:
RecyclerView.dispatchLayout() can try to pull items from the scrap before calling mRecycler.clearOldPositions(). The consequence being is that it was pulling items from the common pool that had positions higher than the adapter size.
1、在滑动的时候,刷新数据,导致数据的list的size为0,当此时滑动就会导致IndexOutOfBoundsException,同理,在rv滑动的时候去请求数据,也会导致这个问题,原理都是越界了.
2、数据变动(移除和增加),执行同步操作时,要保证RecyclerView的Adapter中的数据与需要同步的外部集合数据数量一致!
即每一次外部数据变动(移除和增加)时,都需主动Adapter做一次数据同步操作。以避免数据同步时内外数据不一致
就是clear数据后,没有立马同步notify。
解决方法:
方法一:
其实只要clear旧数据之后刷新rv,再将新的数据显示在rv上,最后再刷新rv就可以了.这是让rv在list的size为0的时候知道了这个变化,重置了list的大小,等新数据重新获取后再刷新,便能得到最新的数据了,崩溃的问题也不会出现.
clear()//清空旧list
notifyDataSetChanged()//刷新数据
add()//增加新数据
notifyDataSetChanged()//刷新数据
方法二:
重写onLayoutChildren方法,加个异常处理
public class MyLinearLayoutManager extends LinearLayoutManager {
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
}
参考:
https://www.jianshu.com/p/fc7267ca1827/
https://blog.youkuaiyun.com/fangxincxy/article/details/100740052
https://stackoverflow.com/questions/30220771/recyclerview-inconsistency-detected-invalid-item-position
https://blog.youkuaiyun.com/zhangyiacm/article/details/78287655
本文探讨了RecyclerView在数据更新时遇到的IndexOutOfBoundsException,原因在于布局刷新前未清空并同步适配器。解决方法强调了确保Adapter与外部数据同步一致的重要性,通过清理旧数据、刷新视图、添加新数据并再次刷新来修复问题。
2069

被折叠的 条评论
为什么被折叠?



