效果:
----------------布局文件-----------------------
<Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="点击开始" android:onClick="start" /> <com.bwei.administrator.view.ProgressView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/progress" />=========自定义布局中==============
public class ProgressView extends View{ private int progress=0; Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if(msg.what==0){ if(progress<100){ progress++; //重新绘制 postInvalidate(); //重新调用 sendEmptyMessageDelayed(0,20); } } } }; public ProgressView(Context context) { super(context); } public ProgressView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public ProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //画一个进度条 首先先画一个圆 Paint paint =new Paint(); paint.setColor(Color.BLACK); paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); canvas.drawCircle(200,200,100,paint); //画一个代表进度的圆弧 RectF rectF = new RectF(100,100,300,300); paint.setColor(Color.RED); paint.setStrokeWidth(5); canvas.drawArc(rectF,-90,360*progress/100,false,paint); //画文字 String text =progress+"%"; paint.setColor(Color.BLACK); paint.setTextSize(40); paint.setStrokeWidth(1); paint.setStyle(Paint.Style.FILL); Rect rect = new Rect(); //测量 paint.getTextBounds(text,0,text.length(),rect); canvas.drawText(text,200-rect.width()/2,200+rect.height()/2,paint); } //对外提供一个启动的方法 public void start(){ handler.sendEmptyMessageDelayed(0,20); } }=============MainActivity中================
progressView = (ProgressView) findViewById(R.id.progress); //点击开始按钮调自定义view中的开始方法
public void start(View view){ progressView.start(); }