<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<EditText
android:id="@+id/et_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="초 입력"
android:inputType="number"
android:textAlignment="center" />
<Button
android:layout_marginStart="10dp"
android:id="@+id/btn_timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="타이머 시작" />
<TextView
android:id="@+id/tv_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:text="남은 초" />
</LinearLayout>
btnTimer.setOnClickListener {
var mSecond: Long = etNumber.text.toString().toLong()
val mTimer = Timer()
// 반복적으로 사용할 TimerTask
mTimerTask = object : TimerTask() {
override fun run() {
val mHandler = Handler(Looper.getMainLooper())
mHandler.postDelayed({
// 반복실행할 구문
mSecond--
Log.d(TAG,"$mSecond")
if (mSecond <= 0) {
mTimer.cancel()
Log.d(TAG,"타이머 종료")
}
binding.tvTime.text = "$mSecond 초"
}, 0)
}
}
mTimer.schedule(mTimerTask, 0, 1000)
Log.d(TAG,"${mSecond}초 타이머 시작")
}