美文网首页
带文字的进度条

带文字的进度条

作者: 小相柳 | 来源:发表于2023-01-10 16:35 被阅读0次
public class TextProgressView extends AppCompatSeekBar {

    private Paint mPaint;
    private Rect mRect;

    private String mText;

    public TextProgressView (@NonNull Context context) {
        this(context, null);
    }

    public TextProgressView (@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TextProgressView (@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
        setClickable(false);
        setFocusable(false);
        setFocusableInTouchMode(false);
        setMax(100);
        setOnTouchListener(new OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
    }

    private void initView() {
        mPaint = new Paint();
        mPaint.setColor(Color.WHITE);
        mPaint.setTextSize(PixelFormat.dip2px(getContext(), 12));
        mPaint.setAntiAlias(true);
        mRect = new Rect();
        mText = "";
    }


    @Override
    protected synchronized void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (TextUtils.isEmpty(this.mText)) return;
        mPaint.getTextBounds(this.mText, 0, this.mText.length(), mRect);
        float progressRatio = (float) getProgress() / getMax();
        canvas.drawText(this.mText, getWidth() * progressRatio - mRect.width()/2f, (getHeight() / 2f) - mRect.centerY(), mPaint);
    }

    public void setKaihuProgress(int progress) {
        this.mText = progress + "%";
        setProgress(progress);
    }

}

相关文章

网友评论

      本文标题:带文字的进度条

      本文链接:https://www.haomeiwen.com/subject/kqyvcdtx.html