欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android实现简单的加载进度条

程序员文章站 2022-07-01 21:54:45
本文实例为大家分享了android实现简单的加载进度条的具体代码,供大家参考,具体内容如下1.效果图2.自定义progressbarpackage com.example.myapplication7...

本文实例为大家分享了android实现简单的加载进度条的具体代码,供大家参考,具体内容如下

1.效果图

Android实现简单的加载进度条

2.自定义progressbar

package com.example.myapplication7;
 
import android.animation.valueanimator;
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.os.bundle;
import android.os.parcelable;
import android.util.attributeset;
import android.view.animation.acceleratedecelerateinterpolator;
import android.widget.progressbar;
 
 
import java.lang.annotation.retention;
import java.lang.annotation.retentionpolicy;
 
import androidx.annotation.intdef;
 
public class circleprogressview extends progressbar {
 
    private int mreachbarsize = utils.dp2px(getcontext(), 2); // 未完成进度条大小
    private int mnormalbarsize = utils.dp2px(getcontext(), 2); // 未完成进度条大小
    private int mreachbarcolor = color.parsecolor("#108ee9"); // 已完成进度颜色
    private int mnormalbarcolor = color.parsecolor("#ffd3d6da"); // 未完成进度颜色
    private int mtextsize = utils.sp2px(getcontext(), 14); // 进度值字体大小
    private int mtextcolor = color.parsecolor("#108ee9"); // 进度的值字体颜色
    private float mtextskewx; // 进度值字体倾斜角度
    private string mtextsuffix = "%"; // 进度值前缀
    private string mtextprefix = ""; // 进度值后缀
    private boolean mtextvisible = true; // 是否显示进度值
    private boolean mreachcapround; // 画笔是否使用圆角边界,normalstyle下生效
    private int mradius = utils.dp2px(getcontext(), 20); // 半径
    private int mstartarc; // 起始角度
    private int minnerbackgroundcolor; // 内部背景填充颜色
    private int mprogressstyle = progressstyle.normal; // 进度风格
    private int minnerpadding = utils.dp2px(getcontext(), 1); // 内部圆与外部圆间距
    private int moutercolor; // 外部圆环颜色
    private boolean needdrawinnerbackground; // 是否需要绘制内部背景
    private rectf rectf; // 外部圆环绘制区域
    private rectf rectinner; // 内部圆环绘制区域
    private int moutersize = utils.dp2px(getcontext(), 1); // 外层圆环宽度
    private paint mtextpaint; // 绘制进度值字体画笔
    private paint mnormalpaint; // 绘制未完成进度画笔
    private paint mreachpaint; // 绘制已完成进度画笔
    private paint minnerbackgroundpaint; // 内部背景画笔
    private paint moutpaint; // 外部圆环画笔
 
    private int mrealwidth;
    private int mrealheight;
 
    @intdef({progressstyle.normal, progressstyle.fill_in, progressstyle.fill_in_arc})
    @retention(retentionpolicy.source)
    public @interface progressstyle {
        int normal = 0;
        int fill_in = 1;
        int fill_in_arc = 2;
    }
 
    public circleprogressview(context context) {
        this(context, null);
    }
 
    public circleprogressview(context context, attributeset attrs) {
        this(context, attrs, 0);
    }
 
    public circleprogressview(context context, attributeset attrs, int defstyleattr) {
        super(context, attrs, defstyleattr);
        obtainattributes(attrs);
        initpaint();
    }
 
    private void initpaint() {
        mtextpaint = new paint();
        mtextpaint.setcolor(mtextcolor);
        mtextpaint.setstyle(paint.style.fill);
        mtextpaint.settextsize(mtextsize);
        mtextpaint.settextskewx(mtextskewx);
        mtextpaint.setantialias(true);
 
        mnormalpaint = new paint();
        mnormalpaint.setcolor(mnormalbarcolor);
        mnormalpaint.setstyle(mprogressstyle == progressstyle.fill_in_arc ? paint.style.fill : paint.style.stroke);
        mnormalpaint.setantialias(true);
        mnormalpaint.setstrokewidth(mnormalbarsize);
 
        mreachpaint = new paint();
        mreachpaint.setcolor(mreachbarcolor);
        mreachpaint.setstyle(mprogressstyle == progressstyle.fill_in_arc ? paint.style.fill : paint.style.stroke);
        mreachpaint.setantialias(true);
        mreachpaint.setstrokecap(mreachcapround ? paint.cap.round : paint.cap.butt);
        mreachpaint.setstrokewidth(mreachbarsize);
 
        if (needdrawinnerbackground) {
            minnerbackgroundpaint = new paint();
            minnerbackgroundpaint.setstyle(paint.style.fill);
            minnerbackgroundpaint.setantialias(true);
            minnerbackgroundpaint.setcolor(minnerbackgroundcolor);
        }
        if (mprogressstyle == progressstyle.fill_in_arc) {
            moutpaint = new paint();
            moutpaint.setstyle(paint.style.stroke);
            moutpaint.setcolor(moutercolor);
            moutpaint.setstrokewidth(moutersize);
            moutpaint.setantialias(true);
        }
    }
 
    private void obtainattributes(attributeset attrs) {
        typedarray ta = getcontext().obtainstyledattributes(attrs, r.styleable.circleprogressview);
        mprogressstyle = ta.getint(r.styleable.circleprogressview_cpv_progressstyle, progressstyle.normal);
        // 获取三种风格通用的属性
        mnormalbarsize = (int) ta.getdimension(r.styleable.circleprogressview_cpv_progressnormalsize, mnormalbarsize);
        mnormalbarcolor = ta.getcolor(r.styleable.circleprogressview_cpv_progressnormalcolor, mnormalbarcolor);
 
        mreachbarsize = (int) ta.getdimension(r.styleable.circleprogressview_cpv_progressreachsize, mreachbarsize);
        mreachbarcolor = ta.getcolor(r.styleable.circleprogressview_cpv_progressreachcolor, mreachbarcolor);
 
        mtextsize = (int) ta.getdimension(r.styleable.circleprogressview_cpv_progresstextsize, mtextsize);
        mtextcolor = ta.getcolor(r.styleable.circleprogressview_cpv_progresstextcolor, mtextcolor);
        mtextskewx = ta.getdimension(r.styleable.circleprogressview_cpv_progresstextskewx, 0);
        if (ta.hasvalue(r.styleable.circleprogressview_cpv_progresstextsuffix)) {
            mtextsuffix = ta.getstring(r.styleable.circleprogressview_cpv_progresstextsuffix);
        }
        if (ta.hasvalue(r.styleable.circleprogressview_cpv_progresstextprefix)) {
            mtextprefix = ta.getstring(r.styleable.circleprogressview_cpv_progresstextprefix);
        }
        mtextvisible = ta.getboolean(r.styleable.circleprogressview_cpv_progresstextvisible, mtextvisible);
 
        mradius = (int) ta.getdimension(r.styleable.circleprogressview_cpv_radius, mradius);
        rectf = new rectf(-mradius, -mradius, mradius, mradius);
 
        switch (mprogressstyle) {
            case progressstyle.fill_in:
                mreachbarsize = 0;
                mnormalbarsize = 0;
                moutersize = 0;
                break;
            case progressstyle.fill_in_arc:
                mstartarc = ta.getint(r.styleable.circleprogressview_cpv_progressstartarc, 0) + 270;
                minnerpadding = (int) ta.getdimension(r.styleable.circleprogressview_cpv_innerpadding, minnerpadding);
                moutercolor = ta.getcolor(r.styleable.circleprogressview_cpv_outercolor, mreachbarcolor);
                moutersize = (int) ta.getdimension(r.styleable.circleprogressview_cpv_outersize, moutersize);
                mreachbarsize = 0;// 将画笔大小重置为0
                mnormalbarsize = 0;
                if (!ta.hasvalue(r.styleable.circleprogressview_cpv_progressnormalcolor)) {
                    mnormalbarcolor = color.transparent;
                }
                int minnerradius = mradius - moutersize / 2 - minnerpadding;
                rectinner = new rectf(-minnerradius, -minnerradius, minnerradius, minnerradius);
 
                break;
            case progressstyle.normal:
                mreachcapround = ta.getboolean(r.styleable.circleprogressview_cpv_reachcapround, true);
                mstartarc = ta.getint(r.styleable.circleprogressview_cpv_progressstartarc, 0) + 270;
                if (ta.hasvalue(r.styleable.circleprogressview_cpv_innerbackgroundcolor)) {
                    minnerbackgroundcolor = ta.getcolor(r.styleable.circleprogressview_cpv_innerbackgroundcolor, color.argb(0, 0, 0, 0));
                    needdrawinnerbackground = true;
                }
                break;
        }
        ta.recycle();
    }
 
    @override
    protected synchronized void onmeasure(int widthmeasurespec, int heightmeasurespec) {
        int maxbarpaintwidth = math.max(mreachbarsize, mnormalbarsize);
        int maxpaintwidth = math.max(maxbarpaintwidth, moutersize);
        int height = 0;
        int width = 0;
        switch (mprogressstyle) {
            case progressstyle.fill_in:
                height = getpaddingtop() + getpaddingbottom()  // 边距
                        + math.abs(mradius * 2);  // 直径
                width = getpaddingleft() + getpaddingright()  // 边距
                        + math.abs(mradius * 2);  // 直径
                break;
            case progressstyle.fill_in_arc:
                height = getpaddingtop() + getpaddingbottom()  // 边距
                        + math.abs(mradius * 2)  // 直径
                        + maxpaintwidth;// 边框
                width = getpaddingleft() + getpaddingright()  // 边距
                        + math.abs(mradius * 2)  // 直径
                        + maxpaintwidth;// 边框
                break;
            case progressstyle.normal:
                height = getpaddingtop() + getpaddingbottom()  // 边距
                        + math.abs(mradius * 2)  // 直径
                        + maxbarpaintwidth;// 边框
                width = getpaddingleft() + getpaddingright()  // 边距
                        + math.abs(mradius * 2)  // 直径
                        + maxbarpaintwidth;// 边框
                break;
        }
 
        mrealwidth = resolvesize(width, widthmeasurespec);
        mrealheight = resolvesize(height, heightmeasurespec);
 
        setmeasureddimension(mrealwidth, mrealheight);
    }
 
    @override
    protected synchronized void ondraw(canvas canvas) {
        switch (mprogressstyle) {
            case progressstyle.normal:
                drawnormalcircle(canvas);
                break;
            case progressstyle.fill_in:
                drawfillincircle(canvas);
                break;
            case progressstyle.fill_in_arc:
                drawfillinarccircle(canvas);
                break;
        }
    }
 
    /**
     * 绘制progress_style_fill_in_arc圆形
     */
    private void drawfillinarccircle(canvas canvas) {
        canvas.save();
        canvas.translate(mrealwidth / 2, mrealheight / 2);
        // 绘制外层圆环
        canvas.drawarc(rectf, 0, 360, false, moutpaint);
        // 绘制内层进度实心圆弧
        // 内层圆弧半径
        float reacharc = getprogress() * 1.0f / getmax() * 360;
        canvas.drawarc(rectinner, mstartarc, reacharc, true, mreachpaint);
 
        // 绘制未到达进度
        if (reacharc != 360) {
            canvas.drawarc(rectinner, reacharc + mstartarc, 360 - reacharc, true, mnormalpaint);
        }
 
        canvas.restore();
    }
 
    /**
     * 绘制progress_style_fill_in圆形
     */
    private void drawfillincircle(canvas canvas) {
        canvas.save();
        canvas.translate(mrealwidth / 2, mrealheight / 2);
        float progressy = getprogress() * 1.0f / getmax() * (mradius * 2);
        float angle = (float) (math.acos((mradius - progressy) / mradius) * 180 / math.pi);
        float startangle = 90 + angle;
        float sweepangle = 360 - angle * 2;
        // 绘制未到达区域
        rectf = new rectf(-mradius, -mradius, mradius, mradius);
        mnormalpaint.setstyle(paint.style.fill);
        canvas.drawarc(rectf, startangle, sweepangle, false, mnormalpaint);
        // 翻转180度绘制已到达区域
        canvas.rotate(180);
        mreachpaint.setstyle(paint.style.fill);
        canvas.drawarc(rectf, 270 - angle, angle * 2, false, mreachpaint);
        // 文字显示在最上层最后绘制
        canvas.rotate(180);
        // 绘制文字
        if (mtextvisible) {
            string text = mtextprefix + getprogress() + mtextsuffix;
            float textwidth = mtextpaint.measuretext(text);
            float textheight = (mtextpaint.descent() + mtextpaint.ascent());
            canvas.drawtext(text, -textwidth / 2, -textheight / 2, mtextpaint);
        }
    }
 
    /**
     * 绘制progress_style_normal圆形
     */
    private void drawnormalcircle(canvas canvas) {
        canvas.save();
        canvas.translate(mrealwidth / 2, mrealheight / 2);
        // 绘制内部圆形背景色
        if (needdrawinnerbackground) {
            canvas.drawcircle(0, 0, mradius - math.min(mreachbarsize, mnormalbarsize) / 2,
                    minnerbackgroundpaint);
        }
        // 绘制文字
        if (mtextvisible) {
            string text = mtextprefix + getprogress() + mtextsuffix;
            float textwidth = mtextpaint.measuretext(text);
            float textheight = (mtextpaint.descent() + mtextpaint.ascent());
            canvas.drawtext(text, -textwidth / 2, -textheight / 2, mtextpaint);
        }
        // 计算进度值
        float reacharc = getprogress() * 1.0f / getmax() * 360;
        // 绘制未到达进度
        if (reacharc != 360) {
            canvas.drawarc(rectf, reacharc + mstartarc, 360 - reacharc, false, mnormalpaint);
        }
        // 绘制已到达进度
        canvas.drawarc(rectf, mstartarc, reacharc, false, mreachpaint);
        canvas.restore();
    }
 
    /**
     * 动画进度(0-当前进度)
     *
     * @param duration 动画时长
     */
    public void runprogressanim(long duration) {
        setprogressintime(0, duration);
    }
 
    /**
     * @param progress 进度值
     * @param duration 动画播放时间
     */
    public void setprogressintime(final int progress, final long duration) {
        setprogressintime(progress, getprogress(), duration);
    }
 
    /**
     * @param startprogress 起始进度
     * @param progress      进度值
     * @param duration      动画播放时间
     */
    public void setprogressintime(int startprogress, final int progress, final long duration) {
        valueanimator valueanimator = valueanimator.ofint(startprogress, progress);
        valueanimator.addupdatelistener(new valueanimator.animatorupdatelistener() {
 
            @override
            public void onanimationupdate(valueanimator animator) {
                //获得当前动画的进度值,整型,1-100之间
                int currentvalue = (integer) animator.getanimatedvalue();
                setprogress(currentvalue);
            }
        });
        acceleratedecelerateinterpolator interpolator = new acceleratedecelerateinterpolator();
        valueanimator.setinterpolator(interpolator);
        valueanimator.setduration(duration);
        valueanimator.start();
    }
 
    public int getreachbarsize() {
        return mreachbarsize;
    }
 
    public void setreachbarsize(int reachbarsize) {
        mreachbarsize = utils.dp2px(getcontext(), reachbarsize);
        invalidate();
    }
 
    public int getnormalbarsize() {
        return mnormalbarsize;
    }
 
    public void setnormalbarsize(int normalbarsize) {
        mnormalbarsize = utils.dp2px(getcontext(), normalbarsize);
        invalidate();
    }
 
    public int getreachbarcolor() {
        return mreachbarcolor;
    }
 
    public void setreachbarcolor(int reachbarcolor) {
        mreachbarcolor = reachbarcolor;
        invalidate();
    }
 
    public int getnormalbarcolor() {
        return mnormalbarcolor;
    }
 
    public void setnormalbarcolor(int normalbarcolor) {
        mnormalbarcolor = normalbarcolor;
        invalidate();
    }
 
    public int gettextsize() {
        return mtextsize;
    }
 
    public void settextsize(int textsize) {
        mtextsize = utils.sp2px(getcontext(), textsize);
        invalidate();
    }
 
    public int gettextcolor() {
        return mtextcolor;
    }
 
    public void settextcolor(int textcolor) {
        mtextcolor = textcolor;
        invalidate();
    }
 
    public float gettextskewx() {
        return mtextskewx;
    }
 
    public void settextskewx(float textskewx) {
        mtextskewx = textskewx;
        invalidate();
    }
 
    public string gettextsuffix() {
        return mtextsuffix;
    }
 
    public void settextsuffix(string textsuffix) {
        mtextsuffix = textsuffix;
        invalidate();
    }
 
    public string gettextprefix() {
        return mtextprefix;
    }
 
    public void settextprefix(string textprefix) {
        mtextprefix = textprefix;
        invalidate();
    }
 
    public boolean istextvisible() {
        return mtextvisible;
    }
 
    public void settextvisible(boolean textvisible) {
        mtextvisible = textvisible;
        invalidate();
    }
 
    public boolean isreachcapround() {
        return mreachcapround;
    }
 
    public void setreachcapround(boolean reachcapround) {
        mreachcapround = reachcapround;
        invalidate();
    }
 
    public int getradius() {
        return mradius;
    }
 
    public void setradius(int radius) {
        mradius = utils.dp2px(getcontext(), radius);
        invalidate();
    }
 
    public int getstartarc() {
        return mstartarc;
    }
 
    public void setstartarc(int startarc) {
        mstartarc = startarc;
        invalidate();
    }
 
    public int getinnerbackgroundcolor() {
        return minnerbackgroundcolor;
    }
 
    public void setinnerbackgroundcolor(int innerbackgroundcolor) {
        minnerbackgroundcolor = innerbackgroundcolor;
        invalidate();
    }
 
    public int getprogressstyle() {
        return mprogressstyle;
    }
 
    public void setprogressstyle(int progressstyle) {
        mprogressstyle = progressstyle;
        invalidate();
    }
 
    public int getinnerpadding() {
        return minnerpadding;
    }
 
    public void setinnerpadding(int innerpadding) {
        minnerpadding = utils.dp2px(getcontext(), innerpadding);
        int minnerradius = mradius - moutersize / 2 - minnerpadding;
        rectinner = new rectf(-minnerradius, -minnerradius, minnerradius, minnerradius);
        invalidate();
    }
 
    public int getoutercolor() {
        return moutercolor;
    }
 
    public void setoutercolor(int outercolor) {
        moutercolor = outercolor;
        invalidate();
    }
 
    public int getoutersize() {
        return moutersize;
    }
 
    public void setoutersize(int outersize) {
        moutersize = utils.dp2px(getcontext(), outersize);
        invalidate();
    }
 
    private static final string state = "state";
    private static final string progress_style = "progressstyle";
    private static final string text_color = "textcolor";
    private static final string text_size = "textsize";
    private static final string text_skew_x = "textskewx";
    private static final string text_visible = "textvisible";
    private static final string text_suffix = "textsuffix";
    private static final string text_prefix = "textprefix";
    private static final string reach_bar_color = "reachbarcolor";
    private static final string reach_bar_size = "reachbarsize";
    private static final string normal_bar_color = "normalbarcolor";
    private static final string normal_bar_size = "normalbarsize";
    private static final string is_reach_cap_round = "isreachcapround";
    private static final string radius = "radius";
    private static final string start_arc = "startarc";
    private static final string inner_bg_color = "innerbgcolor";
    private static final string inner_padding = "innerpadding";
    private static final string outer_color = "outercolor";
    private static final string outer_size = "outersize";
 
    @override
    public parcelable onsaveinstancestate() {
        final bundle bundle = new bundle();
        bundle.putparcelable(state, super.onsaveinstancestate());
        // 保存当前样式
        bundle.putint(progress_style, getprogressstyle());
        bundle.putint(radius, getradius());
        bundle.putboolean(is_reach_cap_round, isreachcapround());
        bundle.putint(start_arc, getstartarc());
        bundle.putint(inner_bg_color, getinnerbackgroundcolor());
        bundle.putint(inner_padding, getinnerpadding());
        bundle.putint(outer_color, getoutercolor());
        bundle.putint(outer_size, getoutersize());
        // 保存text信息
        bundle.putint(text_color, gettextcolor());
        bundle.putint(text_size, gettextsize());
        bundle.putfloat(text_skew_x, gettextskewx());
        bundle.putboolean(text_visible, istextvisible());
        bundle.putstring(text_suffix, gettextsuffix());
        bundle.putstring(text_prefix, gettextprefix());
        // 保存已到达进度信息
        bundle.putint(reach_bar_color, getreachbarcolor());
        bundle.putint(reach_bar_size, getreachbarsize());
 
        // 保存未到达进度信息
        bundle.putint(normal_bar_color, getnormalbarcolor());
        bundle.putint(normal_bar_size, getnormalbarsize());
        return bundle;
    }
 
    @override
    public void onrestoreinstancestate(parcelable state) {
        if (state instanceof bundle) {
            final bundle bundle = (bundle) state;
 
            mprogressstyle = bundle.getint(progress_style);
            mradius = bundle.getint(radius);
            mreachcapround = bundle.getboolean(is_reach_cap_round);
            mstartarc = bundle.getint(start_arc);
            minnerbackgroundcolor = bundle.getint(inner_bg_color);
            minnerpadding = bundle.getint(inner_padding);
            moutercolor = bundle.getint(outer_color);
            moutersize = bundle.getint(outer_size);
 
            mtextcolor = bundle.getint(text_color);
            mtextsize = bundle.getint(text_size);
            mtextskewx = bundle.getfloat(text_skew_x);
            mtextvisible = bundle.getboolean(text_visible);
            mtextsuffix = bundle.getstring(text_suffix);
            mtextprefix = bundle.getstring(text_prefix);
 
            mreachbarcolor = bundle.getint(reach_bar_color);
            mreachbarsize = bundle.getint(reach_bar_size);
            mnormalbarcolor = bundle.getint(normal_bar_color);
            mnormalbarsize = bundle.getint(normal_bar_size);
 
            initpaint();
            super.onrestoreinstancestate(bundle.getparcelable(state));
            return;
        }
        super.onrestoreinstancestate(state);
    }
 
    @override
    public void invalidate() {
        initpaint();
        super.invalidate();
    }
}

3.设置宽高

package com.example.myapplication7;
 
 
import android.content.context;
import android.graphics.bitmap;
import android.graphics.canvas;
import android.graphics.color;
import android.graphics.paint;
import android.graphics.rectf;
import android.graphics.drawable.bitmapdrawable;
import android.graphics.drawable.drawable;
import android.text.textutils;
import android.util.displaymetrics;
import android.view.windowmanager;
 
import java.util.collection;
 
import androidx.annotation.colorres;
 
public class utils {
 
    private static windowmanager windowmanager;
 
    private static windowmanager getwindowmanager(context context) {
        if (windowmanager == null) {
            windowmanager = (windowmanager) context.getsystemservice(context.window_service);
        }
        return windowmanager;
    }
 
    public static float getdensity(context context) {
        return context.getresources().getdisplaymetrics().density;
    }
 
    public static float getfontdensity(context context) {
        return context.getresources().getdisplaymetrics().scaleddensity;
    }
 
    public static displaymetrics getdisplaymetrics(context context) {
        displaymetrics displaymetrics = new displaymetrics();
        getwindowmanager(context).getdefaultdisplay().getmetrics(displaymetrics);
        return displaymetrics;
    }
 
    public static int dp2px(context context, float dp) {
        return (int) (getdensity(context) * dp + 0.5f);
    }
 
    public static int px2dp(context context, float px) {
        return (int) (px / getdensity(context) + 0.5f);
    }
 
    public static int sp2px(context context, float sp) {
        return (int) (getfontdensity(context) * sp + 0.5f);
    }
 
    public static int px2sp(context context, float px) {
        return (int) (px / getfontdensity(context) + 0.5f);
    }
 
    public static int getwindowwidth(context context) {
        return getdisplaymetrics(context).widthpixels;
    }
 
    public static int getwindowheight(context context) {
        return getdisplaymetrics(context).heightpixels;
    }
 
    public static string getpathformat(string path) {
        if (!textutils.isempty(path)) {
            int lastperiodindex = path.lastindexof('.');
            if (lastperiodindex > 0 && lastperiodindex + 1 < path.length()) {
                string format = path.substring(lastperiodindex + 1);
                if (!textutils.isempty(format)) {
                    return format.tolowercase();
                }
            }
        }
        return "";
    }
 
    public static boolean isgif(string url) {
        return "gif".equals(getpathformat(url));
    }
 
    public static bitmap gettextbitmap(context context, int width, int height, int radius, string text, int textsize, @colorres int bgcolor) {
        radius = dp2px(context, radius);
        bitmap bitmap = bitmap.createbitmap(dp2px(context, width), dp2px(context, height), bitmap.config.argb_8888);
        canvas canvas = new canvas(bitmap);
        rectf rect = new rectf(0, 0, canvas.getwidth(), canvas.getheight());
        paint paint = new paint(paint.anti_alias_flag);
        paint.setcolor(context.getresources().getcolor(bgcolor));
        canvas.drawroundrect(new rectf(0, 0, rect.width(), rect.height()), radius, radius, paint);
        paint.setcolor(color.white);
        paint.settextsize(dp2px(context, textsize));
        paint.settextalign(paint.align.center);
        paint.fontmetricsint fontmetrics = paint.getfontmetricsint();
        float baseline = (rect.bottom + rect.top - fontmetrics.bottom - fontmetrics.top) / 2;
        canvas.drawtext(text, rect.centerx(), baseline, paint);
        return bitmap;
    }
 
    public static drawable gettextdrawable(context context, int width, int height, int radius, string text, int textsize, @colorres int bgcolor) {
        return new bitmapdrawable(gettextbitmap(context, width, height, radius, text, textsize, bgcolor));
    }
 
    public static boolean isempty(collection<?> collection) {
        return collection == null || collection.isempty();
    }
 
    public static int getsize(collection<?> collection) {
        return collection == null ? 0 : collection.size();
    }
}

4.主界面

package com.example.myapplication7;
 
 
import android.graphics.bitmap;
import android.graphics.color;
import android.os.bundle;
import android.os.handler;
import android.os.message;
import android.util.log;
import android.view.view;
 
import androidx.annotation.nonnull;
import androidx.annotation.nullable;
import androidx.appcompat.app.appcompatactivity;
 
public class mainactivity extends appcompatactivity {
    private string filename;
    private circleprogressview progressview;
    private bitmap bitmap;
    private int i = 0;
 
    final handler handler = new handler(new handler.callback() {
        @override
        public boolean handlemessage(@nonnull message msg) {
            if (msg.what == 1) {
                //do something
                int a = (int) msg.obj;
                log.e("tag", "handlemessage" + a);
                progressview.setprogress(a * 10);
                if (a == 10) {
                    progressview.setvisibility(view.gone);
                }
            }
            return false;
        }
    });
 
    @override
    protected void oncreate(@nullable bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_main);
        progressview = findviewbyid(r.id.progressview);
        getwindow().settitlecolor(color.rgb(65, 183, 216));
        //主线程中调用:
        new thread(new mythread()).start();
    }
 
    class mythread extends thread {//这里也可用runnable接口实现
 
        @override
        public void run() {
            while (true) {
                try {
                    thread.sleep(500);//每隔1s执行一次
                    message msg = new message();
                    msg.what = 1;
                    i++;
                    msg.obj = i;
                    handler.sendmessage(msg);
                } catch (interruptedexception e) {
                    e.printstacktrace();
                }
            }
        }
    }
 
 
}

5.布局

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
 
 
    <com.example.myapplication7.circleprogressview
        android:id="@+id/progressview"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:progress="0"
        app:cpv_innerpadding="2dp"
        app:cpv_outercolor="@android:color/darker_gray"
        app:cpv_outersize="1dp"
        app:cpv_progressnormalcolor="@android:color/darker_gray"
        app:cpv_progressreachcolor="@color/white"
        app:cpv_progressstyle="fillinnerarc" />
 
</linearlayout>

6.资源文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="circleprogressview">
        <attr name="cpv_progressnormalcolor" format="color" />
        <attr name="cpv_progressreachcolor" format="color" />
        <attr name="cpv_progresstextcolor" format="color" />
        <attr name="cpv_progresstextsize" format="dimension" />
        <attr name="cpv_progresstextoffset" format="dimension" />
        <attr name="cpv_progressnormalsize" format="dimension" />
        <attr name="cpv_progressreachsize" format="dimension" />
        <attr name="cpv_radius" format="dimension" />
        <attr name="cpv_progresstextvisible" format="boolean" />
        <attr name="cpv_progressstartarc" format="integer" />
        <attr name="cpv_progresstextskewx" format="dimension" />
        <attr name="cpv_progresstextprefix" format="string" />
        <attr name="cpv_progresstextsuffix" format="string" />
        <attr name="cpv_innerbackgroundcolor" format="color" />
        <attr name="cpv_progressstyle" format="enum">
            <enum name="normal" value="0" />
            <enum name="fillinner" value="1" />
            <enum name="fillinnerarc" value="2" />
        </attr>
        <attr name="cpv_innerprogresscolor" format="color" />
        <attr name="cpv_innerpadding" format="dimension" />
        <attr name="cpv_outercolor" format="color" />
        <attr name="cpv_outersize" format="dimension" />
        <attr name="cpv_reachcapround" format="boolean" />
    </declare-styleable>
 
</resources>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。