我编写了以下代码在我的 android 应用程序中创建倒计时进度条:
ProgressBar gameTimer;
CountDownTimer gameCountDownTimer;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gameTimer = (ProgressBar)findViewById(R.id.game_timer);
setTimer(10);
}
private void setTimer(int time) {
progress = 100;
final int actualTime = time*1000;
gameTimer.setProgress(progress);
gameCountDownTimer = new CountDownTimer(actualTime, 1000) {
int totalTime = actualTime;
@Override
public void onTick(long millisUntilFinished) {
progress = (int)(( totalTime - millisUntilFinished ) /(double)totalTime * 100);
gameTimer.setProgress(progress);
}
@Override
public void onFinish() {
progress = 0;
gameTimer.setProgress(progress);
endGame();
}
};
}
但问题是定时器总是满的。计时器没有倒计时,也永远不会结束。上面的代码有什么问题?如何让进度条在给定时间内从填充状态到空状态倒计时?
最佳答案
你好像忘了启动 CountDownTimer
,试试这个:
private void setTimer(int time) {
progress = 100;
final int actualTime = time*1000;
gameTimer.setProgress(progress);
gameCountDownTimer = new CountDownTimer(actualTime, 1000) {
int totalTime = actualTime;
@Override
public void onTick(long millisUntilFinished) {
progress = (int)(( totalTime - millisUntilFinished ) /(double)totalTime * 100);
gameTimer.setProgress(progress);
}
@Override
public void onFinish() {
progress = 0;
gameTimer.setProgress(progress);
endGame();
}
}.start();
}
正如描述的那样here .
编辑:
您的 ProgressBar
计数是因为您误解了 millisUntilFinishrd
变量。这个变量在每次滴答时减少。因此,要使您的 ProgressBar 倒计时,您必须替换它:
progress = (int)(( totalTime - millisUntilFinished ) /(double)totalTime * 100);
通过这个:
progress = (int)( millisUntilFinished /(double)totalTime * 100);
关于android - 倒计时进度条不工作 Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24595261/