Android studio实现水平进度条

原文

ProgressBar

用于显示某个耗时操作完成的百分比的组件称为进度条。ProgressBar默认产生圆形进度条。

实现效果图:

MainActivity

java 复制代码
import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.widget.Button;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity {

    private RoundedRectProgressBar bar;
    private Button btn;
    private int progress;
    private Timer timer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bar = (RoundedRectProgressBar) findViewById(R.id.bar);
        btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reset();
            }
        });

    }

    /**
     * 进度条从头到尾跑一次
     */
    private void reset() {
        progress = 0;
        timer = new Timer();
        //以timer为参数,指定某个时间点执行线程
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                bar.setProgress(progress);//设置当前进度
                progress ++;
                if (progress > 100) {
                    timer.cancel();
                }
            }
        }, 0, 300); 0秒后启动任务,以后每隔0.3秒执行一次线程
    }
}

自定义进度条RoundedRectProgressBar.java:

java 复制代码
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

public class RoundedRectProgressBar extends View {

    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private int barColor;
    private int backColor;
    private int textColor;
    private float radius;

    int progress = 0;

    @SuppressLint("NonConstantResourceId")
    public RoundedRectProgressBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        //获取自定义参数的颜色值
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.RoundedRectProgressBar, defStyle, 0);
        int n = a.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            if (attr == R.styleable.RoundedRectProgressBar_backColor) {
                backColor = a.getColor(attr, Color.GRAY);
            } else if (attr == R.styleable.RoundedRectProgressBar_barColor) {
                barColor = a.getColor(attr, Color.GREEN);
            } else if (attr == R.styleable.RoundedRectProgressBar_textColor) {
                textColor = a.getColor(attr, Color.WHITE);
            }
        }
    }


    public RoundedRectProgressBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        radius = this.getMeasuredHeight() / 5;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //背景
        mPaint.setColor(backColor);
        mPaint.setStyle(Paint.Style.FILL);
        canvas.drawRoundRect(new RectF(0, 0, this.getMeasuredWidth(), this.getMeasuredHeight()), radius, radius, mPaint);
        //进度条
        mPaint.setColor(barColor);
        mPaint.setStyle(Paint.Style.FILL);
        canvas.drawRoundRect(new RectF(0, 0, this.getMeasuredWidth() * progress / 100f, this.getMeasuredHeight()), radius, radius, mPaint);
        //进度
        mPaint.setColor(textColor);
        mPaint.setTextSize(this.getMeasuredHeight() / 1.2f);
        String text = "" + progress + "%";
        float x = this.getMeasuredWidth() * progress / 100 - mPaint.measureText(text) - 10;
        float y = this.getMeasuredHeight() / 2f - mPaint.getFontMetrics().ascent / 2f - mPaint.getFontMetrics().descent / 2f;
        canvas.drawText(text, x, y, mPaint);
    }

    /*设置进度条进度, 外部调用*/
    public void setProgress(int progress) {
        if (progress > 100) {
            this.progress = 100;
        } else if (progress < 0) {
            this.progress = 0;
        } else {
            this.progress = progress;
        }
        postInvalidate();
    }
}

activity_main.xml

java 复制代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    tools:context="com.example.progressbarpro.MainActivity">

    <com.example.progressbarpro.RoundedRectProgressBar
        android:id="@+id/bar"
        android:layout_width="match_parent"
        android:layout_height="24dp"
        android:layout_marginTop="100dp"
        app:backColor="#E6E6E6"
        app:barColor="#33CC99"
        app:textColor="#FFFFFF"/>

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="reset"
        android:layout_centerInParent="true"/>
</RelativeLayout>

在values/attrs.xml中添加自定义参数, 使三种颜色可以在布局文件中被配置:

attrs.xml

java 复制代码
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="RoundedRectProgressBar">
        <attr name="backColor" format="color" />
        <attr name="barColor" format="color" />
        <attr name="textColor" format="color" />
    </declare-styleable>

</resources>
相关推荐
娅娅梨3 小时前
Android- Surface, SurfaceView, TextureView, SurfaceTexture 原理图解
android·surface
2501_915918414 小时前
HTTPS 端口号详解 443 端口作用、iOS 抓包方法、常见 HTTPS 抓包工具与网络调试实践
android·网络·ios·小程序·https·uni-app·iphone
程序员码歌4 小时前
明年35岁了,如何破局?说说心里话
android·前端·后端
BillKu5 小时前
推荐 Eclipse Temurin 的 OpenJDK
java·ide·eclipse
非门由也6 小时前
Android studio安装教程——超详细(含安装包安装教程)
android·ide·android studio
平淡风云6 小时前
Android应用添加日历提醒功能
android·日历
骐骥17 小时前
2025-09-08升级问题记录:app提示“此应用专为旧版Android打造..”或“此应用与最新版 Android 不兼容”
android·升级·不兼容·target sdk·专为旧版 android 系统
Zender Han8 小时前
Flutter 视频播放器——flick_video_player 介绍与使用
android·flutter·ios·音视频
尚久龙9 小时前
安卓学习 之 用户登录界面的简单实现
android·运维·服务器·学习·手机·android studio·安卓
Modu_MrLiu9 小时前
Android实战进阶 - 启动页
android·实战进阶·启动页·倒计时场景