Search code examples
androidchronometer

How to use the chronometer as a countdown timer in Android


I have defined a chronometer;

protected Chronometer chrono;
protected int baseTime;
protected int stopTime;
protected long elapsedTime;

My program asks questions to the user and i want to set a timer based on the user's input. I want a timer which starts at 10 to 0. How can i do that?

Also, I want to show the remaining time on the screen.


Solution

  • Use CountDownTImer instead,

     new CountDownTimer(10000, 1000) { //Sets 10 second remaining
    
     public void onTick(long millisUntilFinished) {
         mTextView.setText("seconds remaining: " + millisUntilFinished / 1000);
     }
    
     public void onFinish() {
         mTextView.setText("done!");
     }
    }.start();
    

    Note : It's not possible to start Chronometer reversely because the Chronometer widget only counts up.

    Edit: From API level 24, it is possible to perform count down using chronometer via help of Chronometer#setCountDown(true) method.