问题
I am new to Android Development and trying to make little Game.
CountDownTimer.cancel()
is not working for me.
Any Idea?
Thank Your for your Answer!
CountDownTimer cdt = new CountDownTimer(120000, 1000) {
public void onTick(long millisUntilFinished) {
maxTime = (int) (millisUntilFinished / 1000);
timer.setText(String.valueOf(maxTime));
}
public void onFinish() {
}
};
if (startTimer == true) {
cdt.start();
} else {
cdt.cancel();
}
回答1:
I have to do an assumption right here because the code doesn't show much! apparently you are using the countDownTimer
inside your onCreate
as an inner class so that will trigger the timer when startTimer == true
and it would create the object no matter what! I guess it would be better to create a global instance of CountDownTimer
.
And write your code in this way:
if(startTimer == true) {
cdt = new CountDownTimer(120000, 1000) {
public void onTick(long millisUntilFinished) {
maxTime = (int) (millisUntilFinished / 1000);
timer.setText(String.valueOf(maxTime));
}
public void onFinish() {
}
}.start(); //start the countdowntimer
}
else{
cdt.cancel();
}
来源:https://stackoverflow.com/questions/27730115/countdowntimer-cancel-not-working