OneWay
OneWay

Reputation: 1

How do I reset my timer when the reset button is clicked?

After editing my code I've made this it restarts the timer when the reset button is clicked but it restarts it when another timer is going thus it looks as if there is multiple timers on one time, question "how do i reset the timer if its already been started" if started then stop reset then start again.

  b2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
                counter = 0;
                tx.setText(Integer.toString(counter));
                b.setEnabled(true);

                new CountDownTimer(30000, 1000) {

                 public void onTick(long millisUntilFinished) {
                     tx2.setText("Time remaining: " + millisUntilFinished / 1000);

                 }

                 public void onFinish() {
                     tx2.setText("Finished!");
                     b.setEnabled(false);

                 }
              }.start(); 

        }
    }); 

Upvotes: 0

Views: 841

Answers (1)

Opiatefuchs
Opiatefuchs

Reputation: 9870

Instead of new CountDownTimer, write Your own one inside Your activity. Make it Global:

     public class MyCountDownTimer extends CountDownTimer {
  public MyCountDownTimer(long startTime, long interval) {
   super(startTime, interval);
  }

  @Override
  public void onFinish() {
   //reset button
       tx2.setText("Finished!");
         b.setEnabled(false);
  }

  @Override
  public void onTick(long millisUntilFinished) {
   //do what ever You want
       tx2.setText("Time remaining: " + millisUntilFinished / 1000);
  }
  }

Then in Your Activity:

   MyCountDownTimer timer=null;
   long startTime = 10000;
   long interval = 1000;

in OnCreate() initialize it:

   timer = new MyCountDownTimer(startTime, interval);

Start Your Timer where You need it:

   timer.start();

Cancel it when needed:

   timer.cancel();

And start it again:

    timer = new MyCountDownTimer(startTime, interval);
    timer.start();

Upvotes: 1

Related Questions