How to create a simple countdown timer in Kotlin?

Andy Fedoroff picture Andy Fedoroff · Jan 8, 2019 · Viewed 51.6k times · Source

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) {
        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
    }
    public void onFinish() {
        mTextField.setText("Time's finished!");
    }
}.start();

How can I do it using Kotlin?

Answer

Danail Alexiev picture Danail Alexiev · Jan 8, 2019

You can use Kotlin objects:

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

    override fun onFinish() {...}
}
timer.start()