报错原因
查看了源码,
@Nullable
ViewHolder tryGetViewHolderForPositionByDeadline(int position,
boolean dryRun, long deadlineNs) {
if (position < 0 || position >= mState.getItemCount()) {
throw new IndexOutOfBoundsException("Invalid item position " + position
+ "(" + position + "). Item count:" + mState.getItemCount()
+ exceptionLabel());
}
- 快速滑动RecyclerView 时,清空数据和更新数据非线程安全,数据不同步
- 解决Step1:
自定义LinearLayoutManager 或者GrideLayoutManager,将onLayoutChildren 捕捉异常。
public class CommonGalleryLayoutManager extends LinearLayoutManager {
public CommonGalleryLayoutManager(Context context) {
super(context);
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
}
- Step2:
清空数据不要使用adapter.getData.clear ,请直接adapter.setData(null) 或者如果你使用了BRVAH库的话,直接使用
adapter.setNewInstance(null)