进度条是我们平时开发过程中经常使用的。本文来介绍一下动态环境进度条的实现方法。
自定义CustomView,继承自DynamicCircle。
package com.gucheng.dynamiccircle;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by suolong on 2018/4/1.
*/
public class CustomCircle extends View {
private int mWidth;
private int mHeight;
private RectF mRectF;
private int mCurrentProgress = 0;
private int mMaxProgress = 100;
public CustomCircle(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setStrokeWidth(10);
paint.setColor(Color.rgb(0x3a, 0x58, 0x5f));
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.BLUE);
mWidth = getWidth();
mHeight = getHeight();
mRectF = new RectF();
setRectFPosition(mRectF);
canvas.drawArc(mRectF, -90, ((float) mCurrentProgress % mMaxProgress) / mMaxProgress * 360, false, paint);
}
private void setRectFPosition(RectF mRectF) {
mRectF.left = 10; // 左上角x
mRectF.top = 10; // 左上角y
mRectF.right = mWidth - 10; // 左下角x
mRectF.bottom = mWidth - 10; // 右下角y
}
public void setProgress(int currentProgress) {
mCurrentProgress = currentProgress;
invalidate();
}
}
在这个view中定义了一个public方法setProgress去改变当前画圆弧的进度。每次setProgress的时候调用invalidate()使画面重绘。
在MainActivity中每间隔一定时间就调用setProgress方法改变进度。
package com.gucheng.dynamiccircle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
private Handler handler = new Handler();
private int mCurrentProgress = 0;
CustomCircle mCustomCircle;
private Runnable runnable = new Runnable() {
@Override
public void run() {
mCurrentProgress += 5;
mCustomCircle.setProgress(mCurrentProgress);
handler.postDelayed(this, 30);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCustomCircle = (CustomCircle)findViewById(R.id.custom_circle);
handler.postDelayed(runnable, 500);
}
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(runnable);
}
}
最终效果如下图:
github代码地址如下
https://github.com/gucheng3116/DynamicCircle