Reputation: 63
I'm working on an Android application where I would like the CountdownTimer to skip 5 seconds when the reset button is pressed. For example, if the reset button is pressed when count down timer is at t = 15, the timer will skip the next five seconds and hence the timer will now display t = 10. Here's what I tried but it didn't work:
Button Code:
buttonReset = (Button) findViewById(R.id.ButtonReset);
buttonReset.setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View v) {
TextView output = (TextView) findViewById(R.id.Display);
r = 1;
output.setText("");
resetStatus = true;
}
}
);
Edit: I have updated the timer code. Now, I cancel the old timer and start a new one.
Count down timer code:
public void start()
{
new CountDownTimer(59*1000, 1000)
{
TextView timer = (TextView) findViewById(R.id.Timer);
public void onTick(long millisUntilFinished)
{
int TimeSeconds = (int) millisUntilFinished/1000;
if (resetStatus)
{
cancel();
TimeSeconds = TimeSeconds - 5;
final int finalTimeSeconds = TimeSeconds;
new CountDownTimer(finalTimeSeconds*1000, 1000)
{
@Override
public void onTick(long millisUntilFinished) {
if (finalTimeSeconds >= 10)
{
//displays time
timer.setText("00:" + finalTimeSeconds);
}
else
{
//displays time
timer.setText("00:0" + finalTimeSeconds);
}
resetStatus = false;
}
@Override
public void onFinish() {
gameOverDialogue();
}
}.start();
}
else
{
if (TimeSeconds >= 10)
{
//displays time
timer.setText("00:" + TimeSeconds);
}
else
{
//displays time
timer.setText("00:0" + TimeSeconds);
}
}
}
public void onFinish()
{
gameOverDialogue();
}
}.start();
}
When I press the reset button now, the timer skips 5 seconds after which the display freezes. However, the timer keeps ticking and reaches 0. I think it's because in the second count down timer the final
variable finalTimeSeconds
is used instead of TimeSeconds
. Any suggestions?
Thanks in advance
Upvotes: 0
Views: 1168
Reputation: 2177
The problem is that your display changes with your flag, but the timer doesn't. Your assignment
int TimeSeconds = (int) millisUntilFinished/1000;
runs on every tick. You check the resetStatus
flag and adjust the TextView, but that has no effect on the actual timer. The next time it ticks, it will have the proper (undeducted) time remaining.
Solving this problem can be kind of tricky. You can, as @MoraS suggested, create a new CountdownTimer each time a deduction is warranted. This solution will work, but if you expect deductions often, it may slow down the app a bit.
My suggestion would be to keep track of the total number of deductions, use that to keep the TextView up to date, and cancel the timer early as appropriate.
Upvotes: 0
Reputation: 719
In your code you only modify, one time, the time to display, but your CountDownTimer is not affected by this edit.
You should restart another CountDownTimer with the new delay and cancel the current one.
Upvotes: 0