Kotlin 以3秒后退出应用为例,用handler+postDelayed() 实现倒计时

1、初始化三个属性

    private var mTime = 3

    private var mHandler: Handler = Handler()

    private val mRunnable: Runnable = object : Runnable {
        override fun run() {
            // TODO: 倒计时逻辑
             if (mTime == 0) {
                System.exit(0)
            }
            mTime--
            tv_agree_no.text = "不同意(${mTime})"

            // 每隔一秒调用
            mHandler.postDelayed(this, 1_000L) 
       
        }
    }

2、需要触发的时候调用

     mHandler.removeCallbacks(mRunnable)
     mHandler.postDelayed(mRunnable, 1_000L)

 

你可能感兴趣的:(Kotlin 以3秒后退出应用为例,用handler+postDelayed() 实现倒计时)