进度条加载
package com.baway.a1509a_view.widget; 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.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import com.baway.a1509a_view.R; import java.util.Timer; import java.util.TimerTask; /** * */ public class MyPb extends View { private float cx; private float cy; private float radius; private Paint paint; private int sweepAngle; private int color; public MyPb(Context context) { this(context, null); } public MyPb(Context context, @Nullable AttributeSet attrs) { super(context, attrs); //获取自定义的属性 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyPb); //获取颜色 color = a.getColor(R.styleable.MyPb_circle_color, Color.BLACK); radius = a.getDimension(R.styleable.MyPb_circle_radius, 20); cx = a.getDimension(R.styleable.MyPb_circle_x, 100); cy = a.getDimension(R.styleable.MyPb_circle_y, 100); //需要回收 a.recycle(); paint = new Paint(); paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { if (sweepAngle > 360) { return; } sweepAngle += 1; //刷新View //这个方法只能在主线程刷新UI // invalidate(); //这个方法,也是刷新UI,并且可以在子线程刷新 postInvalidate(); } } , 1000, 20); } @Override protected void onDraw(Canvas canvas) { paint.setColor(color); paint.setStrokeWidth(5); canvas.drawCircle(cx, cy, radius, paint); paint.setColor(Color.RED); RectF rectF = new RectF(cx - radius, cy - radius, cx + radius, cy + radius); canvas.drawArc(rectF, -90, sweepAngle, false, paint); //绘制文字 int progress = (int) (sweepAngle / 360f * 100); paint.setStrokeWidth(0); paint.setColor(Color.BLACK); paint.setTextSize(15); canvas.drawText(progress + "%", cx - 5, cy, paint); } }
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyPb">
<attr name="circle_color" format="color"></attr>
<attr name="circle_radius" format="dimension"></attr>
<attr name="circle_x" format="dimension"></attr>
<attr name="circle_y" format="dimension"></attr>
</declare-styleable>
</resources>