Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop a timer that hasn't finished and then start a new one?

I'm attempting to do a guessing game, of sorts. The issue is my timer bleeds into the next one after a question is answered (button pressed) and a new timer starts. This leads to two timers changing a textview at different intervals, which is not how it's supposed to be. I'd like to know how to stop my previous countdown and start a new one. Thanks! Here's my code:

button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
 final TextView textic = (TextView) findViewById(R.id.button1);
                                long total = 30000;
            final CountDownTimer Count = new CountDownTimer(total, 1000) {

                public void onTick(long millisUntilFinished) {
                    textic.setText("Time Left: " + millisUntilFinished / 1000);
                }
                public void onFinish() {
                    textic.setText("OUT OF TIME!");
                    finish();
                }
                }; 
                Count.start();
like image 288
MattDementous Avatar asked Mar 08 '12 21:03

MattDementous


1 Answers

Heven't tested the code but I would use something like this:

 final TextView textic = (TextView) findViewById(R.id.button1);
 final android.os.CountDownTimer Count = new android.os.CountDownTimer(total, 1000) {
       public void onTick(long millisUntilFinished) {
           textic.setText("Time Left: " + millisUntilFinished / 1000);
       }
       public void onFinish() {
           textic.setText("OUT OF TIME!");
       }
 }; 
 button.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
          Count.cancel();
          Count.start();
      }
   });
like image 171
MariuszP Avatar answered Oct 27 '22 19:10

MariuszP