java.lang.IndexOutOfBoundsException: Invalid item position 0(0). Item count:0
View view = recycler.getViewForPosition(0); 报异常
解决方法:
@Override
public void onMeasure(@NonNull RecyclerView.Recycler recycler, @NonNull RecyclerView.State state, int widthSpec, int heightSpec) {
//获取count判断,必须要有
int count = state.getItemCount();
if (count > 0) {
if (measuredHeight <= 0) {
View view = recycler.getViewForPosition(0);
measureChild(view, widthSpec, heightSpec);
measuredWidth = View.MeasureSpec.getSize(widthSpec);
measuredHeight = view.getMeasuredHeight() * getSpanCount();
}
setMeasuredDimension(measuredWidth, measuredHeight);
} else {
super.onMeasure(recycler, state, widthSpec, heightSpec);
}
}
本文详细解析了java.lang.IndexOutOfBoundsException异常在RecyclerView中的原因,并提供了一种有效的解决方案。通过在onMeasure方法中增加对item数量的判断,避免了试图访问不存在的位置导致的错误。
759

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



