概述
写倒计时CountDown的正确姿势
- 方法一(初级) 利用Handler来实现
申明
private var countDownHandler = Handler()
var countDownTime = Constants.RETURN_TIME//自己设定的时间
private val countDown = object : Runnable {
override fun run() {
if (countDownTime >= 0) {
countDownHandler.postDelayed(this, 1000)//每秒
//执行逻辑
//可以动态的更新UI:还有5s返回之类的
} else {
//停止的逻辑
}
countDownTime--
}
}
调用
viewBinding.defaultPaneDefault.defaultPaneDefaultQr.setOnClickListener {
//点击事件逻辑
countDownTime = Constants.RETURN_TIME
countDownHandler.postDelayed(
countDown, 0)
}
- 方法二(进阶) 利用CountDown并封装成Util实现
兼顾生命周期, 防止内存泄漏
UtilKCountDown
package com.mozhimen.basick.utilk
import android.os.CountDownTimer
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
/**
* @ClassName UtilKCountDown
* @Description TODO
* @Author Kolin Zhao / Mozhimen
* @Date 2022/9/26 15:57
* @Version 1.0
*/
class UtilKCountDown(private val _lifecycleOwner: LifecycleOwner) : DefaultLifecycleObserver {
private var _utilKCountDownListener: IUtilKCountDownListener? = null
private var _countDownTimer: CountDownTimer? = null
init {
_lifecycleOwner.lifecycle.addObserver(this)
}
interface IUtilKCountDownListener {
fun onTick(millisUntilFinished: Long)
fun onFinish()
}
fun start(countDownMilliseconds: Long, listener: IUtilKCountDownListener? = null) {
listener?.let { _utilKCountDownListener = it }
_countDownTimer = UtilKCountDownTimer(countDownMilliseconds)
_countDownTimer!!.start()
}
fun stop() {
_countDownTimer?.cancel()
_countDownTimer = null
}
override fun onDestroy(owner: LifecycleOwner) {
stop()
_lifecycleOwner.lifecycle.removeObserver(this)
}
private inner class UtilKCountDownTimer(countDownMilliseconds: Long) : CountDownTimer(countDownMilliseconds, 1000) {
override fun onTick(millisUntilFinished: Long) {
_utilKCountDownListener?.onTick(millisUntilFinished)
}
override fun onFinish() {
_utilKCountDownListener?.onFinish()
}
}
}
调用
private val _countDown: UtilKCountDown = UtilKCountDown(this)
private companion object {
val TIME_DELAY = 5 * 1000L
}
override fun initData(savedInstanceState: Bundle?) {
_countDown.start(TIME_DELAY, object : UtilKCountDown.IUtilKCountDownListener {
override fun onTick(millisUntilFinished: Long) {
}
override fun onFinish() {
}
})
}
最后
以上就是大气蜜蜂为你收集整理的【Android,kotlin】写倒计时CountDown的正确姿势的全部内容,希望文章能够帮你解决【Android,kotlin】写倒计时CountDown的正确姿势所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复