分割线我们利用RecyclerView的addItemDecoration(ItemDecoration fromHtml) 新建一个类来看看到底是什么:
public class CategoryItemDecoration extends RecyclerView.ItemDecoration { @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { } }
有两个方法getItemOffsets()这里我一般指定偏移量就可以了,就是分割线占多少高度,或者说是画在什么位置,你总的给我留出位置来;onDraw()我们可以直接去绘制,绘制什么都可以因为有Canvas ,但一般都是绘制Drawable。
public class CategoryItemDecoration extends RecyclerView.ItemDecoration { private Paint mPaint; public CategoryItemDecoration(int color) { // 直接绘制颜色 只是用来测试 mPaint = new Paint(); mPaint.setColor(color); mPaint.setAntiAlias(true); } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { int childCount = parent.getChildCount(); // 获取需要绘制的区域 Rect rect = new Rect(); rect.left = parent.getPaddingLeft(); rect.right = parent.getWidth() - parent.getPaddingRight(); for (int i = 0; i < childCount; i++) { View childView = parent.getChildAt(i); rect.top = childView.getBottom(); rect.bottom = rect.top + 20; // 直接利用Canvas去绘制一个矩形 在留出来的地方 c.drawRect(rect, mPaint); } } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { // 在每个子View的下面留出20px来画分割线 outRect.bottom += 20; } }