Android倒计时进度条
发表于|更新于
|阅读量:
这里使用CountDownTimer类来实现了一个倒计时进度条的库:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| import android.os.CountDownTimer; import android.widget.ProgressBar; public class CountdownProgressBar { private ProgressBar progressBar; private CountDownTimer countDownTimer; public CountdownProgressBar(ProgressBar progressBar, long countDownInterval) { this.progressBar = progressBar; startCountdown(countDownInterval); } private void startCountdown(long countDownInterval) { countDownTimer = new CountDownTimer(countDownInterval, 1000) { @Override public void onTick(long millisUntilFinished) { // 更新进度条的UI progressBar.setProgress((int) (millisUntilFinished / 1000)); } @Override public void onFinish() { // 倒计时完成时的操作 progressBar.setProgress(0); } }.start(); } public void cancel() { countDownTimer.cancel(); } }
|
使用也很简单:
1 2 3 4 5 6 7 8
| // 假设你的ProgressBar在布局文件中定义了id为progress_bar ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar); // 创建倒计时进度条,倒计时10秒 CountdownProgressBar countdownProgressBar = new CountdownProgressBar(progressBar, 10000); // 当你需要取消倒计时时 countdownProgressBar.cancel();
|