最近在工作中遇见个奇怪现象,即RecyclerView 采用GridLayoutManager进行布局,当系统是LTR时,数据刷新时变现正常;但是如果是RTL情况下,每次数据添加或莫名其妙向上滚动一个单元格。测试提出这个问题后就开始疯狂找问题,最终定位是由于GridLayoutManager内部方法findReferenceChild引起的。
GridLayoutManager源码如下:
View findReferenceChild(RecyclerView.Recycler recycler, RecyclerView.State state, int start, int end, int itemCount) { ensureLayoutState(); View invalidMatch = null; View outOfBoundsMatch = null; final int boundsStart = mOrientationHelper.getStartAfterPadding(); final int boundsEnd = mOrientationHelper.getEndAfterPadding(); final int diff = end > start ? 1 : -1; for (int i = start; i != end; i += diff) { final View view = getChildAt(i); final int position = getPosition(view); if (position >= 0 && position < itemCount) { final int span = getSpanIndex(recycler, state, position); if (span != 0) { continue; } if (((RecyclerView.LayoutParams) view.getLayoutParams()).isItemRemoved()) { if (invalidMatch == null) { invalidMatch = view; // removed item, least preferred } } else if (mOrientationHelper.getDecoratedStart(view) >= boundsEnd || mOrientationHelper.getDecoratedEnd(view) < boundsStart) { if (outOfBoundsMatch == null) { outOfBoundsMatch = view; // item is not visible, less preferred } } else {