Kotlin和Handler实现倒计时

Kotlin和Handler实现倒计时

1、布局文件

<?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=".countDown.CountDownActivity">

    <TextView
        android:id="@+id/tvCountDown"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="剩余60秒"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="24dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

2、Activity当中逻辑处理

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import com.example.myapplication.R
import kotlinx.android.synthetic.main.activity_count_down.*

class CountDownActivity : AppCompatActivity() {

    private val handler = Handler()
    private var mCountNum = 60

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_count_down)

        tvCountDown.setOnClickListener {
            handler.postDelayed(countDown, 0)
        }
    }

    private val countDown = object : Runnable {

        override fun run() {

            tvCountDown.text = "剩余" + mCountNum + "秒"
            tvCountDown.isEnabled = false
            if (mCountNum > 0) {
                handler.postDelayed(this, 1000)
            } else {
                tvCountDown.text = "重新倒计时"
                tvCountDown.isEnabled = true
                mCountNum = 60
            }
            mCountNum--
        }
    }
    
    private fun removeCountDOwn() {
        
        handler.removeCallbacks(countDown)
    }
}

猜你喜欢

转载自blog.csdn.net/nsacer/article/details/103774683