当前位置 : 主页 > 编程语言 > java >

自定义下载进度条按钮

来源:互联网 收集:自由互联 发布时间:2021-06-28
gistfile1.txt 重写onDraw方法实现, @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //背景 mPaint.setColor(progressbtn_backgroud_color); RectF r1 = new RectF(0, 0, width, height); canvas.drawRoundRect(r1, radi
gistfile1.txt
重写onDraw方法实现,
 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //背景
        mPaint.setColor(progressbtn_backgroud_color);
        RectF r1 = new RectF(0, 0, width, height);
        canvas.drawRoundRect(r1, radius, radius, mPaint);
        //进度
        mPaint.setColor(progressbtn_backgroud_second_color);
        int newWidth = progress * space;
        if (newWidth >= width) {
            newWidth = width;
        }

        RectF r2 = new RectF(0, 0, newWidth, height);
        canvas.drawRoundRect(r2, radius, radius, mPaint);
        //字体
        if (progress == 0) {
            text = "开始";
        } else if (progress >= 100) {
            text = "结束";
        } else {
            text = "下载中 " + progress + " % ";
        }
        //获取文字的高宽
        Rect rect = new Rect();
        mTextPaint.getTextBounds(text, 0, text.length(), rect);
        int textWidth = rect.width();//文本的宽度
        canvas.drawText(text, (width - textWidth) / 2, height / 2, mTextPaint);
        postDelayed(runnable, 30);
    }

线程控制

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (!isStart) {
                return;
            }
            if (progress > 100) {
                return;
            }
            progress++;
            postInvalidate();
        }
    };

    public void start() {
        //进度
        isStart = true;
        post(runnable);
    }

    public void pause() {
        //进度
        isStart = false;
        post(runnable);
    }
网友评论