编辑
自定义ItemDecoration
本文访问次数:0
  1. 1. 元素间隔
  2. 2. 在元素下方绘图
  3. 3. 在元素上方绘图

通过继承ItemDecoration类可以实现下面的几个效果

元素间隔

通过getItemOffsets方法实现元素间隔,相当于margin或者padding的效果。

publick void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state){
    outRect.top = 0;
    outRect.left = 0;
    outRect.bottom = Utils.getPixel(getContext(), 10);
    outRect.right = 0;
}

在元素下方绘图

通过onDraw方法可以在元素下方绘图

public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state){
    int width = c.getWidth();
    int height = c.getHeight();
    int strokeWidth = 5;
    Paint paint = new Paint();
    paint.setStrokeWidth(strokeWidth);
    paint.setAntiAlias(true);
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
    c.drawLine(0, height - strokeWidth, width, height - strokeWidth, paint);
}

注意Canvas的大小为整个RecyclerView的大小。

在元素上方绘图

通过onDrawOver方法可以在元素下方绘图

public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state){
    int width = c.getWidth();
    int height = c.getHeight();
    int strokeWidth = 5;
    Paint paint = new Paint();
    paint.setStrokeWidth(strokeWidth);
    paint.setAntiAlias(true);
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
    c.drawLine(0, height - strokeWidth, width, height - strokeWidth, paint);
}

需要输入验证码才能留言

没有任何评论