用kotlin的写法写一个 CountDownTimer
时间: 2024-05-09 18:18:20 浏览: 140
好的,以下是用Kotlin写一个CountDownTimer的示例代码:
```
class MyCountDownTimer(val millisInFuture: Long, val countDownInterval: Long) {
private var isTimerRunning = false
private var timeLeft: Long = millisInFuture
private var timer: CountDownTimer? = null
private var onTickListener: ((Long) -> Unit)? = null
private var onFinishListener: (() -> Unit)? = null
fun start() {
if (!isTimerRunning) {
timer = object : CountDownTimer(timeLeft, countDownInterval) {
override fun onTick(millisUntilFinished: Long) {
timeLeft = millisUntilFinished
onTickListener?.invoke(millisUntilFinished)
}
override fun onFinish() {
isTimerRunning = false
onFinishListener?.invoke()
}
}.start()
isTimerRunning = true
}
}
fun cancel() {
timer?.cancel()
isTimerRunning = false
}
fun setTimeLeft(timeLeft: Long) {
this.timeLeft = timeLeft
}
fun setOnTickListener(onTickListener: (Long) -> Unit) {
this.onTickListener = onTickListener
}
fun setOnFinishListener(onFinishListener: () -> Unit) {
this.onFinishListener = onFinishListener
}
}
```
使用方法如下:
```
val myCountDownTimer = MyCountDownTimer(60000, 1000)
myCountDownTimer.setOnTickListener { millisUntilFinished ->
// Update UI with time left
}
myCountDownTimer.setOnFinishListener {
// Do something when timer finishes
}
myCountDownTimer.start()
```
这个CountDownTimer会持续60秒,并且每隔1秒回调一次onTickListener,最后结束时调用onFinishListener。如果需要修改时间,可以调用setTimeLeft方法。如果需要停止计时器,可以调用cancel方法。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)