Android 实现圆形倒计时进度
时间: 2023-11-11 14:55:45 浏览: 304
android实现倒计时
4星 · 用户满意度95%
要在Android上实现圆形倒计时进度,可以使用自定义View和计时器来实现。下面是实现的步骤:
1. 创建一个自定义的View类,继承自View,用于绘制圆形进度。
2. 在自定义View类中添加一个计时器,用于更新倒计时的进度。
3. 在onDraw方法中绘制圆形进度条,可以使用Canvas和Paint类来实现。
4. 在计时器中更新倒计时的进度,并调用invalidate方法来触发View的重绘。
下面是一个简单的示例代码:
```java
public class CountdownCircleView extends View {
private Paint mPaint;
private int mProgress;
private CountDownTimer mCountDownTimer;
public CountdownCircleView(Context context) {
super(context);
init();
}
public CountdownCircleView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(10);
mPaint.setColor(Color.BLUE);
mProgress = 100;
mCountDownTimer = new CountDownTimer(60000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
mProgress = (int) (millisUntilFinished / 1000);
invalidate();
}
@Override
public void onFinish() {
mProgress = 0;
invalidate();
}
};
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int radius = Math.min(centerX, centerY) - mPaint.getStrokeWidth() / 2;
RectF rectF = new RectF(centerX - radius, centerY - radius, centerX + radius, centerY + radius);
float sweepAngle = 360f * mProgress / 60;
canvas.drawArc(rectF, -90, sweepAngle, false, mPaint);
}
public void startCountdown() {
mCountDownTimer.start();
}
}
```
使用方式:
```java
CountdownCircleView countdownView = findViewById(R.id.countdown_view);
countdownView.startCountdown();
```
阅读全文