我想构建一个5秒钟的计时器,在1秒钟的间隔内计数到0,然后重置为5秒的初始值。计时器需要不断运行。看完这个帖子后, Android - loop part of the code every 5 seconds
我使用了CountDownTimer类并在onFinish()方法中调用了start()方法,这样当计时器结束时,它会重置为5.它会在连续循环上运行,但是我注意到在第一个循环之后,它要么倒计时4-3-2-1-0或5-3-2-1-0。 有人可以向我解释为什么会这样吗?
private long START_TIME_IN_MILLIS = 5000;
//set up our variables
private CountDownTimer timer;
private TextView textView;
private Button starttimer;
private long mTimeLeftInMillis = START_TIME_IN_MILLIS;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view_countdown);
starttimer = findViewById(R.id.button_start_pause);
//set onclik listener when touch imput button
starttimer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
beginTime();
}
});
}
//creating my own method
private void beginTime() {
timer = new CountDownTimer(mTimeLeftInMillis, 1000) {
@Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
@Override
public void onFinish() {
start();
}
}.start();
}
private void updateCountDownText(){
int minutes= (int) (mTimeLeftInMillis / 1000)/ 60;
int seconds= (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
textView.setText(timeLeftFormatted);
}
}
答案 0 :(得分:0)
试试这个
@Override
public void onFinish() {
mTimeLeftInMillis = START_TIME_IN_MILLIS;
}