Android View 自定义RangeSeekBar范围选择器 走在View进阶之路

本文详细介绍了如何创建一个自定义的RangeSeekBar,包括重写onMeasure以确定大小,实现SeekBar按钮的绘制,触摸事件监听以实现拖动交互,以及添加视觉反馈和刻度模式。此外,还支持自定义UI样式和背景颜色,并提供了使用教程链接。
摘要由CSDN通过智能技术生成

前段时间群里兄弟项目中有类似这样的需求



我看到兄弟受苦受难,于心不忍。又因事不关己,打算高高挂起。正在爱恨纠结之时,日神对我说:没事多造点轮子,你的人生会有很多收获。这波鸡汤让我深受触动,于是决定拯救兄弟于水生火热之中。



重写onMeasure 决策自身大小


显而易见当可以拖拽的范围极限为零时,也就是RangeSeeBar正常显示能够接受的极限,粗略一看:Width > 2 * Height

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
	int widthSize = MeasureSpec.getSize(widthMeasureSpec);
	int heightSize = MeasureSpec.getSize(heightMeasureSpec);
	if (heightSize * 2 > widthSize) {
		setMeasuredDimension(widthSize, widthSize / 2);
	} else {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}
}

绘制拖动条背景 凡事先从简单开始

public class RangeSeekBar extends View {
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

    private int lineTop, lineBottom, lineLeft, lineRight;
    private int lineCorners;
    private int lineWidth;
    private RectF line = new RectF();

    public RangeSeekBar(Context context) {
        this(context, null);
    }

    public RangeSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        if (heightSize * 2 > widthSize) {
            setMeasuredDimension(widthSize, (int) (widthSize / 2));
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        int seekBarRadius = h / 2;
        /**
         * 属性 left right top bottom 描述了SeekBar按钮的位置
         * 蓝后根据它们预先设置确定出 RectF line 背景的三维
         * lineCorners 圆滑的边缘似乎会比直角更好看
         */
        lineLeft = seekBarRadius;
        lineRight = w - seekBarRadius;
        lineTop = seekBarRadius - seekBarRadius / 4;
        lineBottom = seekBarRadius + seekBarRadius / 4;
        lineWidth = lineRight - lineLeft;
        line.set(lineLeft, lineTop, lineRight, lineBottom);
        lineCorners = (int) ((lineBottom - lineTop) * 0.45f);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(0xFFD7D7D7);
        canvas.drawRoundRect(line, lineCorners, lineCorners, paint);
    }
}

很明显这里设计seekBarRadius作为SeekBar按钮的半径,值为RangeSeekBar自身高度一半。那么为了使默认状态的SeekBar按钮圆心能压在背景条的起点和终点
背景条的起点和终点当然就分别相对于自身宽度往内部偏移一个半径咯。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值