public class MarginDecoration extends RecyclerView.ItemDecoration {
private int margin;
private Paint mPaint ;
public MarginDecoration(Context context) {
margin = 10 ; //间隔 px ,修改成自己需要的
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.GRAY);
}
/**
* 针对RecyclerView本身 。
* 可以在此进行更加精细的控制,比如每行的间隔颜色显示不一样。
* 颜色绘制的原理就是: 将每个item 之间的间隙绘制上颜色即可。
*/
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDraw(c, parent, state);
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View view = parent.getChildAt(i);
int index = parent.getChildAdapterPosition(view);
if (index == 0) {
continue;
}
int color= i%2==0 ? Color.parseColor("#06cebc") :Color.parseColor("#3b99ff") ;
mPaint.setColor( color);
float dividerTop = view.getTop() - margin;
float dividerLeft = parent.getPaddingLeft() + margin;
float dividerBottom = view.getTop();
float dividerRight = parent.getWidth() - parent.getPaddingRight() - margin;
c.drawRect(dividerLeft, dividerTop, dividerRight, dividerBottom, mPaint);
}
}
/**
* 针对 每一个 item
*/
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
if (parent.getChildAdapterPosition(view) != 0) {
outRect.top = margin; // 间隔 ,outRect.top / bottom /left /right
}
}
}
//使用
recyclerViewSwipe.addItemDecoration(new MarginDecoration(getActivity()));