/**
* recyclerview设置GridLayoutManager 等分margin宽度时的自定义ItemDecoration
*/
public class RecyclerViewMarginDecoration extends RecyclerView.ItemDecoration {
private int mMargin;
int spanCount;
/**
* @param context 上下文
* @param spanCount 每行的item数量
* @param margin 均宽的magin值
*/
public RecyclerViewMarginDecoration(Context context, int spanCount, int margin) {
mMargin = ScreenUtil.dpAdapt((Activity) context, margin, 375);
this.spanCount = spanCount;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
RecyclerView.LayoutManager manager = parent.getLayoutManager();
if (manager instanceof GridLayoutManager) {
final GridLayoutManager gridManager = ((GridLayoutManager) manager);
GridLayoutManager.SpanSizeLookup spanSizeLookup = gridManager.getSpanSizeLookup();
int spanSize = spanSizeLookup.getSpanSize(parent.getChildAdapterPosition(view));
if (spanSize == 1) {
if (parent.getChildLayoutPosition(view) % spanCount == 0) {
outRect.set(mMargin, 0, mMargin / 2, 0);
} else {
int lineNumber = (parent.getChildLayoutPosition(view) / spanCount) + 1;//找到行数
int lastItem = lineNumber * spanCount - 1; //找到这一行的最后一个item位置
if (parent.getChildLayoutPosition(view) == lastItem) {
outRect.set(mMargin / 2, 0, mMargin, 0);
} else {
outRect.set(mMargin / 2, 0, mMargin / 2, 0);
}
}
}
}
}
}
使用:
recyclerview.addItemDecoration(new RecyclerViewMarginDecoration(this,2,15));
|