最近在使用GridLayoutManager的时候,效果什么的都是好好的,突然在一台设备上发现item高度和设定值不一样。找了好久的原因发现是老版本GridLayoutManager的坑。特作此篇做个记录,并简单分析GridLayoutManager的源码。
GridLayoutManager继承自LinearLayoutManager,LinearLayoutManager初始化的时候默认方向是垂直的。GridLayoutManager测量child的主要重写layoutChunk方法。因此,我们重点分析一下layoutChunk方法。
while (count < mSpanCount && layoutState.hasMore(state) && remainingSpan > 0) {
int pos = layoutState.mCurrentPosition;
final int spanSize = getSpanSize(recycler, state, pos);
if (spanSize > mSpanCount) {
throw new IllegalArgumentException("Item at position " + pos + " requires " +
spanSize + " spans but GridLayoutManager has only " + mSpanCount
+ " spans.");
}
remainingSpan -= spanSize;
if (remainingSpan < 0) {
break; // item did not fit into this row or column
}
View view = layoutState.next(recycler);
if (view == null) {
break;
}
consumedSpanCount += spanSize;
mSet[count] = view;
count++;
}
这个方法是来处理GridLayoutManager跨列问题的,GridLayoutManager给我们提供了SpanSizeLookup这个类来实现item占用spanSize的问题。比如设置mSpanCount等于4,mSpanSizeLookup.getSpanSize(adapterPosition);
来获取adapterPosition占用的列数。当占用的列数累加超过mSpanCount就跳出,并把当行的View存储到mSet[]中。
// we should assign spans before item decor offse