androidkotlincountdowntimer

How to create a simple countdown timer in Kotlin?


I know how to create a simple countdown timer in Java. But I'd like to create this one in Kotlin.

package android.os;

new CountDownTimer(20000, 1000) {
    public void onTick(long millisUntilFinished) {
        txtField.setText("seconds remaining: " + millisUntilFinished / 1000);
    }
    public void onFinish() {
        txtField.setText("Time's finished!");
    }
}.start();

How can I do it using Kotlin?


Solution

  • You can use Kotlin objects:

    val timer = object: CountDownTimer(20000, 1000) {
        override fun onTick(millisUntilFinished: Long) {...}
    
        override fun onFinish() {...}
    }
    timer.start()