MattDementous
MattDementous

Reputation: 97

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();

Upvotes: 5

Views: 8900

Answers (2)

ViratBhavsar
ViratBhavsar

Reputation: 104

finish CountDownTimer in On finish

    @Override
    public void onFinish() {
        Log.v(TAG, "On Finish");
        textvieew.setText("your text");
        countDownTimer.cancel();

    }

Upvotes: 0

MariuszP
MariuszP

Reputation: 136

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();
      }
   });

Upvotes: 7

Related Questions