Sé cómo crear un temporizador de cuenta regresiva simple en Java. Pero me gustaría crear este en 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();¿Cómo puedo hacerlo usando Kotlin?
Puedes usar objetos de Kotlin:
val timer = object: CountDownTimer(20000, 1000) { override fun onTick(millisUntilFinished: Long) {...} override fun onFinish() {...} } timer.start()Resolví mi problema con el temporizador en Kotlin así:
class Timer { private val job = SupervisorJob() private val scope = CoroutineScope(Dispatchers.Default + job) private fun startCoroutineTimer(delayMillis: Long = 0, repeatMillis: Long = 0, action: () -> Unit) = scope.launch(Dispatchers.IO) { delay(delayMillis) if (repeatMillis > 0) { while (true) { action() delay(repeatMillis) } } else { action() } } private val timer: Job = startCoroutineTimer(delayMillis = 0, repeatMillis = 20000) { Log.d(TAG, "Background - tick") doSomethingBackground() scope.launch(Dispatchers.Main) { Log.d(TAG, "Main thread - tick") doSomethingMainThread() } } fun startTimer() { timer.start() } fun cancelTimer() { timer.cancel() } //... }He usado Coroutines para un temporizador.
El cronómetro se puede configurar para contar hacia atrás y me parece la forma más fácil.
Agregue la vista Cronómetro en su diseño xml, ejemplo
<Chronometer android:id="@+id/view_timer" tools:targetApi="24" android:layout_width="wrap_content" android:layout_height="wrap_content"/>Luego en tu actividad o fragmento:
view_timer.isCountDown = true view_timer.base = SystemClock.elapsedRealtime() + 20000 view_timer.start()