我试图实现一个计时器计数器,但我看到的只是CountDown
并且我不想倒计时,我只想从00:00开始每秒钟总和一秒到60:00,我一直试图实现这个:
1 .- Android timer? How? - Answer
2.- Chronometer
他们根本没有帮助我..你能指导我如何从00:00开始到60:00结束吗?
当Usama Zafar提出他的答案时,我更新了代码以控制此CountDownTimer
,以防您需要它...
我创建了
CountDownTimer cdtTimer;
然后我必须startTimer()
的方法开始计算它的时间:
private void StartTimer(){
final long EndTime = 3600;
cdtTimer = new CountDownTimer(EndTime*1000, 1000) {
public void onTick(long millisUntilFinished) {
long secondUntilFinished = (long) (millisUntilFinished/1000);
long secondsPassed = (EndTime - secondUntilFinished);
long minutesPassed = (long) (secondsPassed/60);
secondsPassed = secondsPassed%60;
tvCounterTimer.setText(String.format("%02d", minutesPassed) + ":" + String.format("%02d", secondsPassed));
}
public void onFinish() {
tvCounterTimer.setText("done!");
}
}.start();
}
然后,无论我想取消这个CountDownTimer
,我只需要
cdtTimer.cancel();
答案 0 :(得分:2)
实现Timer的最简单方法是显然使用Android官方指南中所述的CountDown
:
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
但根据您的要求,您不想倒计时,而是希望计算到达60分钟。我们怎么做才是一个有趣的问题。您可以尝试使用以下方法实现Runnable并在每个tick上以毫秒为单位获取系统时间:System.currentTimeMillis()
。
它往往变得复杂吗?那么为什么不玩CountDown Timer并让它能满足我们的需求呢?我们怎么做?请注意以下代码:
long StartTime = 0; //Starting from 00:00
long EndTime = 3600; //End at min:sec converted to seconds
new CountDownTimer(EndTime*1000, 1000) {
public void onTick(long millisUntilFinished) {
long secondUntilFinished = (long) (millisUntilFinished/1000);
long secondsPassed = (EndTime - secondUntilFinished);
long minutesPassed = (long) (secondsPassed/60);
secondsPassed = secondsPassed%60;
// So now at this point your time will be: minutesPassed:secondsPassed
mytextView.setText(String.format("%02d", minutesPassed) + ":" + String.format("%02d", secondsPassed));
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
代码很容易理解。如果您仍然有任何疑问,请发表评论,我会解决。希望这有用。