问题:使用GridLayoutManager添加RecyclerView.ItemDecoration出现item不相等的问题。
解决:通过等比计算间距宽度。
核心算法:
int eachWidth = (spanCount - 1) * spaceMiddle / spanCount; 计算等比间距
int top = spaceTop;
int left = position % spanCount * (spaceMiddle - eachWidth);
if (left >= eachWidth) { // 左边距离出现大于等比间距,就使用等比间距
left = eachWidth;
}
int right = eachWidth - left;
int bottom = 0;
outRect.set(left, top, right, bottom);
public class ItemDecorationRight extends RecyclerView.ItemDecoration {
private int spaceMiddle;
private int spaceTop;
private int spanCount;
public ItemDecorationRight(Context context, int spanCount) {
this.spanCount = spanCount;
this.spaceTop = DisplayHelps.dip2px(context, 15);
this.spaceMiddle = DisplayHelps.dip2px(context, 35);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildLayoutPosition(view);
if (position <= 8) {
int eachWidth = (spanCount - 1) * spaceMiddle / spanCount;
int top = spaceTop;
int left = position % spanCount * (spaceMiddle - eachWidth);
if (left >= eachWidth) {
left = eachWidth;
}
int right = eachWidth - left;
int bottom = 0;
outRect.set(left, top, right, bottom);
}
}
}