今天测试突然找我说项目在刷新数据时偶现crash情况,经过反复测试终于重现出此错误日志,如图所示,看到此错误信息我当时也是一脸懵逼,没有报具体哪段代码的错误信息,而是报RecyclerView
内部错误,于是经过google一番终于找到此错误原因,在此记录下解决方法:
1、创建一个继承LinearLayoutManager的类,重写onLayoutChildren方法,捕获异常,使项目不会crash掉:
public class WrapContentLinearLayoutManager extends LinearLayoutManager {
//... constructor
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException e) {
Log.e("probe", "meet a IOOBE in RecyclerView");
}
}
}
2、采用notifyItemRangeRemoved + notifyItemRangeInserted方式:
int oldContentSize = itemsBeanList.size();//获取刷新前数据长度
itemsBeanList.clear();
adapter.notifyItemRangeRemoved(0,oldContentSize );
itemsBeanList.addAll(newContentList);//添加新数据
//下拉刷新时oldContentSize为0,上拉加载时为之前数据长度
adapter.notifyItemRangeInserted(oldContentSize,newContentList.size());
总结
经自己测试,上面两个方法都是有效的,这个错误原因应该是adapter中数据集不一致而导致的,只需要解决外部数据集和内部数据集保持同步更新即可。有关notifyItemRangeRemoved 和notifyItemRangeInserted的含义,这里就不多说了,想了解的可以去API文档中阅读,多读读文档对自己很有帮助的。哈哈!