kotlin 一个方法实现倒计时

var countDownTimer:CountDownTimer?=null

 

 

//时间  倒计时   入参long类型
countDownTimer = object : CountDownTimer(10000000, 1000) {
    @SuppressLint("SetTextI18n")
    override fun onTick(millisUntilFinished: Long) {
        if ([email protected]()) {
            val day = millisUntilFinished / (1000 * 24 * 60 * 60) //单位天
            val hour =
                (millisUntilFinished - day * (1000 * 24 * 60 * 60)) / (1000 * 60 * 60)
            //单位时
            val minute =
                (millisUntilFinished - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60)) / (1000 * 60)
            //单位分
            val second =
                (millisUntilFinished - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60) - minute * (1000 * 60)) / 1000
            //单位秒
            remaining_text_day.text = "剩余"+day+"天结束"

            var days = day.toString()
            if (days.length<2){//如果是 1 2 3 4 5 6 7 8 9 前边加0
                days = "0$days"
            }
            text_day.text = days

            var hours = hour.toString()
            if (hours.length<2){//如果是 1 2 3 4 5 6 7 8 9 前边加0
                hours = "0$hours"
            }
            text_house.text = hours

            var minutes = minute.toString()
            if (minutes.length<2){//如果是 1 2 3 4 5 6 7 8 9 前边加0
                minutes = "0$minutes"
            }
            text_points.text = minutes

            var seconds = second.toString()
            if (seconds.length<2){//如果是 1 2 3 4 5 6 7 8 9 前边加0
                seconds = "0$seconds"
            }
            text_seconds.text = seconds

            val stringByFormat = TimeUtil.getStringByFormat(100000000, "yyyy-MM-dd HH:mm:ss")
            end_time.text = stringByFormat+"结束"
        }
    }

    /**
     * 倒计时结束后调用的
     */
    override fun onFinish() {}
}
countDownTimer?.start()

 

 

override fun onDestroy() {//销毁置空
    super.onDestroy()
    if (countDownTimer != null) {
        countDownTimer?.cancel()
        countDownTimer = null;
    }
}

 

 

TimeUtil   详见上一篇  超全的日期处理工具类

 

 

 

你可能感兴趣的:(kotlin 一个方法实现倒计时)