CountDownTimer

MainActivity


import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import com.qrvvacuna_desarrollo_qrv.countdowntimer.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private var timer: CountDownTimer? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.apply {
bStart.setOnClickListener {
startCountDownTimer(20000)
}
}
}

private fun startCountDownTimer(timeMillis: Long){
timer?.cancel()
timer = object : CountDownTimer(timeMillis, 1){
override fun onTick(timeM: Long) {
binding.tvTimer.text = timeM.toString()
}

override fun onFinish() {
binding.tvTimer.text = "Finish"
}

}.start()
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/tvTimer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0000"
android:textColor="@color/black"
android:textSize="34sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.333" />

<Button
android:id="@+id/bStart"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:text="start"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Timer"
android:textColor="@color/black"
app:layout_constraintBottom_toTopOf="@+id/tvTimer"
app:layout_constraintEnd_toEndOf="@+id/tvTimer"
app:layout_constraintStart_toStartOf="@+id/tvTimer" />

</androidx.constraintlayout.widget.ConstraintLayout>

Добавить комментарий

Ваш адрес email не будет опубликован.