viewpager2导致的mViews下标越界问题
viewpager2种在嵌套一个RecyclerView场景:左右滑动,上下滑动,出现mViews为null问题。
//RecyclerView布局为
new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
由于使用viewpager2导致布局缓存的销毁,会导致调用了StaggeredGridLayoutManager#onDetachedFromWindow方法。由于我没有设置viewpager2的缓存数量(启动不多加载,启动快),在频繁切换的时候,会调用此方法calculateCachedStart。
class Span {static final int INVALID_LINE = Integer.MIN_VALUE;ArrayList<View> mViews = new ArrayList<>();int mCachedStart = INVALID_LINE;int mCachedEnd = INVALID_LINE;int mDeletedSize = 0;final int mIndex;Span(int index) {mIndex = index;}int getStartLine(int def) {if (mCachedStart != INVALID_LINE) {return mCachedStart;}if (mViews.size() == 0) {return def;}calculateCachedStart();return mCachedStart;}void calculateCachedStart() {final View startView = mViews.get(0);final LayoutParams lp = getLayoutParams(startView);mCachedStart = mPrimaryOrientation.getDecoratedStart(startView);if (lp.mFullSpan) {LazySpanLookup.FullSpanItem fsi = mLazySpanLookup.getFullSpanItem(lp.getViewLayoutPosition());if (fsi != null && fsi.mGapDir == LayoutState.LAYOUT_START) {mCachedStart -= fsi.getGapForSpan(mIndex);}}}
}
导致方法【calculateCachedStart】中的mViews.get(0)出现了下标越界。。。
设置一下页面缓存数,让它不要销毁,就没事了。
// 设置左右缓存的页数为1binding.supermarketVp.setOffscreenPageLimit(1);