I am now making a game where at first the player will see the colors of the buttons, and then after 5 seconds the color of all buttons will blank out and user has to pick those that are with the same color so as to win.
For the 5 seconds of waiting, I have used the handler to wait for execution, and at the same time displaying the countdown of the 5 second by the CountDownTimer for the player to know how long is the remaining time.
If the user gives up the current game, he can click the restart button to start another game.
Everything runs fine, and when the player clicks the restart button, the program also know need to wait for 5 seconds before blanking out all the buttons’ color.
Question:
It is about the display of the 5 second countdown. If the user start 1 game, the countdown start counts. If the user presses the restart button again, eg, after 3 seconds, the original countdown does not terminate, instead, it will display both countdown at the same time. I would like to ask how to terminate the previous countdown if the player presses the restart button.
Codes:
protected void onCreate(Bundle savedInstanceState)
{
...other actions
restart.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
handler1.removeCallbacks(txtClearRun);
SetNewQ();
}
});
SetNewQ();
} // end onCreate
private void SetNewQ()
{
MyCount5sec counter5sec = new MyCount5sec(5000,1000);
counter5sec.start();
...other actions below
}
public class MyCount5sec extends CountDownTimer
{
public MyCount5sec(long millisInFuture, long countDownInterval) {super(millisInFuture, countDownInterval);}
@Override
public void onFinish()
{
ButtonRemainTime= (Button) findViewById(R.id.button_remaintime);
ButtonRemainTime.setText("Add oil!!");
// game then start by blanking out all the colors
}
@Override
public void onTick(long millisUntilFinished)
{
ButtonRemainTime= (Button) findViewById(R.id.button_remaintime);
ButtonRemainTime.setText("" + millisUntilFinished/1000);
}
I know what your question is asking for but i’d personally adjust my setup in the following way. If your
CountDownTimerclass implements not much else, you can actually declare the class afieldand instantiate it the one fell swoop.The benefit of doing it like this is that you’d always be referring to the same object. you wouldn’t have to make a new timer on each
onClickand then manage cancelling the other one. In fact, you wouldn’t even have tocancelat all because callingstarton the timer early on this same timer object will just restart it.