Kotlin 倒计时
时间: 2024-01-25 16:13:20 浏览: 29
以下是两种基于Kotlin Flow实现倒计时功能的例子:
1. 在Activity中实现倒计时功能:
```kotlin
mBtnStart.setOnClickListener {
mCountDownView.startCountDown(10) {
showToast("倒计时结束")
}
}
```
2. 使用Flow实现倒计时功能:
```kotlin
private fun countDownByFlow(
max: Int,
scope: CoroutineScope,
onTick: (Int) -> Unit,
onFinish: (() -> Unit)? = null,
): Job {
return flow {
for (num in max downTo 0) {
emit(num)
if (num != 0) delay(1000)
}
}.flowOn(Dispatchers.Main)
.onEach { onTick.invoke(it) }
.onCompletion { cause ->
if (cause == null) onFinish?.invoke()
}
.launchIn(scope)
}
```
相关问题
使用kotlin实现倒计时功能
在Kotlin中实现倒计时功能的方法如下:
1. 创建一个计时器类,该类包含一个计时器和一个计时器任务:
```
class CountDownTimer(val totalTime: Long, val interval: Long, val onFinish: () -> Unit, val onTick: (Long) -> Unit) {
private var remainingTime = totalTime
private var timer: Timer? = null
fun start() {
timer = Timer()
timer?.scheduleAtFixedRate(object : TimerTask() {
override fun run() {
remainingTime -= interval
if (remainingTime <= 0) {
onFinish()
stop()
} else {
onTick(remainingTime)
}
}
}, 0, interval)
}
fun stop() {
timer?.cancel()
}
}
```
2. 在Activity或Fragment中实例化CountDownTimer类,设置总时间、间隔时间、倒计时结束回调和每秒钟回调:
```
val countDownTimer = CountDownTimer(
totalTime = 60000, // 总时间60秒
interval = 1000, // 每秒钟回调一次
onFinish = {
// 倒计时结束回调
// do something...
},
onTick = { remainingTime ->
// 每秒钟回调
// 更新UI
textView.text = "${remainingTime / 1000}秒"
}
)
```
3. 调用CountDownTimer的start方法开始倒计时:
```
countDownTimer.start()
```
4. 如果需要在用户退出Activity或Fragment时停止计时器,可以在onDestroy方法中调用CountDownTimer的stop方法:
```
override fun onDestroy() {
super.onDestroy()
countDownTimer.stop()
}
```
用kotlin写一个计时器
好的,下面是一个简单的计时器示例:
```kotlin
import java.util.*
import kotlin.concurrent.timer
fun main() {
val scanner = Scanner(System.`in`)
println("请输入计时时间(单位:秒):")
val seconds = scanner.nextInt()
var count = seconds
val timerTask = timer(period = 1000) {
count--
if (count <= 0) {
cancel()
} else {
println("还剩 $count 秒")
}
}
}
```
这个程序会要求用户输入计时时间(以秒为单位),然后开始倒计时。每秒钟会输出当前剩余时间,直到计时结束。在这个示例中,我们使用了 `java.util.Timer` 类来实现计时器,每秒钟执行一次计时任务。