继承RecyclerView.ItemDecoration后,在getItemOffsets()中添加间隔即可
public class CommonSpaceItemDecoration extends RecyclerView.ItemDecoration {
private int spaceTop;
private int spaceBottom;
private int spaceLeft;
private int spaceRight;
private boolean isOneNo;
/**
* @param spaceLeft
* @param spaceTop
* @param spaceRight
* @param spaceBottom
* @param isDp 是否是dp
*/
public CommonSpaceItemDecoration(int spaceLeft, int spaceTop, int spaceRight, int spaceBottom, boolean isDp) {
if (isDp) {
spaceLeft = YxpSizeUtils.dp2px(spaceLeft);
spaceTop = YxpSizeUtils.dp2px(spaceTop);
spaceRight = YxpSizeUtils.dp2px(spaceRight);
spaceBottom = YxpSizeUtils.dp2px(spaceBottom);
}
this.spaceTop = spaceTop;
this.spaceBottom = spaceBottom;
this.spaceLeft = spaceLeft;
this.spaceRight = spaceRight;
}
/**
* @param spaceLeft
* @param spaceTop
* @param spaceRight
* @param spaceBottom
* @param isDp 是否是dp
* @param isOneNo 第一个不偏移
*/
public CommonSpaceItemDecoration(int spaceLeft, int spaceTop, int spaceRight, int spaceBottom, boolean isDp, boolean isOneNo) {
if (isDp) {
spaceLeft = YxpSizeUtils.dp2px(spaceLeft);
spaceTop = YxpSizeUtils.dp2px(spaceTop);
spaceRight = YxpSizeUtils.dp2px(spaceRight);
spaceBottom = YxpSizeUtils.dp2px(spaceBottom);
}
this.isOneNo = isOneNo;
this.spaceTop = spaceTop;
this.spaceBottom = spaceBottom;
this.spaceLeft = spaceLeft;
this.spaceRight = spaceRight;
}
@Override
public void getItemOffsets(Rect outRect, View view,
RecyclerView parent, RecyclerView.State state) {
if (isOneNo) {
if (parent.getChildAdapterPosition(view) != 0) {
outRect.left = spaceLeft;
outRect.right = spaceRight;
outRect.bottom = spaceBottom;
outRect.top = spaceTop;
}
} else {
outRect.left = spaceLeft;
outRect.right = spaceRight;
outRect.bottom = spaceBottom;
outRect.top = spaceTop;
}
}
}
网友评论