Divider.java 1.37 KB
Newer Older
gaodapeng's avatar
gaodapeng committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
package com.miya.fastcashier.widget;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

/**
 * 通用的RecyclerDivider
 */
public class Divider extends RecyclerView.ItemDecoration {
    private Paint paint;
    private int divideWidth;

gaodapeng's avatar
gaodapeng committed
16 17
    public Divider(int divideWidth, int color) {
        super();
gaodapeng's avatar
gaodapeng committed
18 19
        this.paint = new Paint();
        paint.setAntiAlias(true);
gaodapeng's avatar
gaodapeng committed
20 21
        paint.setColor(color);
        this.divideWidth = divideWidth;
gaodapeng's avatar
gaodapeng committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int left = parent.getPaddingStart();
        int right = parent.getMeasuredWidth() - parent.getPaddingEnd();
        View child;
        int childPosition;
        int validChildCount = parent.getChildCount();
        for (int i = 0; i < validChildCount; i++) {
            child = parent.getChildAt(i);
            childPosition = parent.getChildAdapterPosition(child);
            if (childPosition == validChildCount - 1) {
                break;
            }
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
            int top = child.getBottom() + layoutParams.bottomMargin;
            int bottom = top + divideWidth;
            c.drawRect(left, top, right, bottom, paint);
        }
    }
}