Android自定义进度条的简单使用

实现如图所示:

Android自定义进度条的简单使用_第1张图片

代码如下:

1、SimpleView2

package com.example.testdialog;

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;

import androidx.annotation.Nullable;

public class SimpleView2 extends View {

    //画笔
    private Paint mPaint;

    private int progress;//进度
    private int bgcolor;//背景颜色
    private int procolor;//进度颜色

    // view的宽度
    private int mWidth;
    // view的高度
    private int mHeight;

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

    public SimpleView2(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initAttrs(attrs);
        //初始化画笔
        mPaint=new Paint();
    }
    private void initAttrs(AttributeSet attrs){
        if(attrs==null){
            return;
        }
        mWidth=400;
        mHeight=30;
        //获得所有的属性
        TypedArray array=getContext().obtainStyledAttributes(attrs,R.styleable.SimpleView2);
        progress=array.getInteger(R.styleable.SimpleView2_progress,0);
        bgcolor=array.getColor(R.styleable.SimpleView2_bgcolor, Color.GRAY);
        procolor=array.getColor(R.styleable.SimpleView2_procolor,Color.CYAN);
        array.recycle();//回收TypedArray
    }

    /** View在绘制View之前,会先调用onMeasure方法去设置View的宽和高
     * 当你设置组件宽度为match_parent时,发现组件没法自动适配屏幕宽度。
     * 为了让组件能够满足我们适应屏幕宽高的需求,我们需要在onMeasure方法中对组件进行根据模式测量宽高:
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec){
        int widthMode=MeasureSpec.getMode(widthMeasureSpec);
        int width=MeasureSpec.getSize(widthMeasureSpec);
        int heightMode=MeasureSpec.getMode(heightMeasureSpec);
        int height=MeasureSpec.getSize(widthMeasureSpec);
        int temp=measureSize(widthMode,width);
        mWidth=temp==0?mWidth:temp;
        temp=measureSize(heightMode,height);
        mHeight=temp==0?mHeight:temp;
        setMeasuredDimension(mWidth,mHeight);

    }
    private int measureSize(int mode,int defsize){
        int size=0;
        switch (mode){
            case MeasureSpec.UNSPECIFIED:
            case MeasureSpec.AT_MOST:
                break;
            case MeasureSpec.EXACTLY:
                size=defsize;
                break;
        }
        return size;
    }


    /**
     * 在onDraw方法中绘制我们需要的进度条
     * @param canvas
     */
    @Override
    protected void onDraw(Canvas canvas){
        mPaint.setColor(bgcolor);//设置进度条背景颜色
        RectF rectF=new RectF();//背景的矩形
        rectF.set(3,3,mWidth-3,mHeight-3);
        canvas.drawRoundRect(rectF,3,3,mPaint);
        mPaint.setColor(procolor);
        RectF proRect=new RectF();//进度的矩形
        proRect.set(3,3,mWidth*((float)progress/100),mHeight-3);
        canvas.drawRoundRect(proRect,3,3,mPaint);
    }

    /**
     * 设置进度条的进度
     * @param progress
     */
    public void setProgress(int progress){
        if(progress<0||progress>100){
            return;
        }
        this.progress=progress;
        //重绘组件
        postInvalidate();
    }
}

2、MainActivity

package com.example.testdialog;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class MainActivity extends AppCompatActivity {
    private SimpleView2 simpleView2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        simpleView2=findViewById(R.id.progress);
        new Thread(new Runnable() {
            int progress=0;
            @Override
            public void run() {
                while(progress<100) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    progress += 10;
                    if(progress==100){
                        progress = 0;
                    }
                    Message msg = handler.obtainMessage();
                    msg.what = progress;
                    handler.sendMessage(msg);

                }

            }
        }).start();
    }

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg){
            int progress=msg.what;
            simpleView2.setProgress(progress);
        }
    };
}

3、在value目录建立attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="SimpleView2">
        <attr name="progress" format="integer"/>
        <attr name="bgcolor" format="color"/>
        <attr name="procolor" format="color"/>
    </declare-styleable>
</resources>

4、布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.example.testdialog.SimpleView2
        android:id="@+id/progress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        app:progress="0" />


</RelativeLayout>

你可能感兴趣的:(android)