android自定义调节器控件 —— RegulatorView

RegulatorView效果图:

RegulatorView实现步骤:

    1.新建java类RegulatorView.java,继承View类

    2.定义必要基础属性,及为其附初始值

private final static int BTN_RADIUS=20;//拖动按钮的半径
private final static int BTN_CIRCLE_RADIUS=6;//拖动按钮的圆心半径
private final static int BAR_HEIGHT=6;//进度条的高度
private String barColor="#a82894ff";
private String circleColor="#902894ff";
private String txtColor="#ff2894ff";

private float currentValue=50;//当前值
private float maxValue=100;//最大值
private float minValue=0;//最小值
private boolean isShowText=false;//是否显示文字提示
private boolean isCanAdjust=false;//是否可以调节

    3.实现init()方法,实例化画笔等属性

private void init(){
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
//        mPaint.setTextSize(16);
        mBound = new Rect();//用于测量文字的宽度,以便准确无误地显示文字内容
        mPaint.getTextBounds(maxValue+"",0,(maxValue+"").length(),mBound);
    }

    4.实现onMeasure(int arg0,int arg1)方法,测量控件的高度和宽度(由于是横向调节器,所以只需重新测量高度值就可以了,高度值和拖动按钮的半径有关)

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
  
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int height ;

        if (heightMode == MeasureSpec.EXACTLY){
            height = heightSize;
        } else {
            height = getPaddingTop() + BTN_RADIUS*2 + getPaddingBottom();
        }
        setMeasuredDimension(widthSize, height);
    }

    5.实现onDraw()方法,根据相应的属性值绘制界面

        绘制分为4步进行,具体实现请看文章后面的完整代码;这一步的实现已经可以看到控件的显示效果

@Override
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
protected void onDraw(Canvas canvas) {
    drawBg(canvas);//绘制整体背景
    drawBar(canvas);//绘制当前值的占比条
    drawBtn(canvas);//绘制当前值得调节按钮
    drawTxt(canvas);//绘制文本值(显示最大最小值及当前值)
}

    6.实现onTouchEvent()方法以响应事件,实现调节功能,需要注意一点,界面的刷新操作是在设置当前值时才能调用(即:界面是否刷新取决于当前值是否改变,调节最大最小值时,当前值也需要调节,以确保整个控件逻辑的正确)

public void setCurrentValue(float currentValue) {
    this.currentValue = currentValue>maxValue?maxValue:currentValue;
    this.currentValue = this.currentValue<minValue?minValue:this.currentValue;
    if(onValueChangeListener!=null) onValueChangeListener.onValueChange(this.currentValue);
    invalidate();
}

public void setMaxValue(float maxValue) {
    this.maxValue = maxValue<minValue?minValue:maxValue;
    setCurrentValue(currentValue);
    mPaint.getTextBounds(this.maxValue+"",0,(this.maxValue+"").length(),mBound);
}

public void setMinValue(float
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值