我可以通过使用cancel()(timer.cancel())函数成功停止计时器。但是如何恢复呢?我搜索了很多代码,但所有内容都是Java。我在科特林需要它。你能给我建议吗?我使用代码:
val timer = object : CountDownTimer(60000, 1000) {
override fun onTick(millisUntilFinished: Long) {
textView3.text = (millisUntilFinished / 1000).toString() + ""
println("Timer : " + millisUntilFinished / 1000)
}
override fun onFinish() {}
}
编辑:
在课堂上:
var currentMillis: Long = 0 // <-- keep millisUntilFinished
// First creation of your timer
var timer = object : CountDownTimer(60000, 1000) {
override fun onTick(millisUntilFinished: Long) {
currentMillis = millisUntilFinished // <-- save value
textView3.text = (millisUntilFinished / 1000).toString() + ""
println("Timer : " + millisUntilFinished / 1000)
}
override fun onFinish() {}
}
在onCreate()中:
timer.start()
TextView2.setOnClickListener {
//Handle click
timer.cancel()
}
TextView3.setOnClickListener {
//Handle click
timer = object : CountDownTimer(currentMillis, 1000) {
override fun onTick(millisUntilFinished: Long) {
currentMillis = millisUntilFinished
textView3.text = (millisUntilFinished / 1000).toString() + ""
println("Timer : " + millisUntilFinished / 1000)
}
override fun onFinish() {}
}
timer.start()
}
答案 0 :(得分:1)
我的建议:保留millisUntilFinished
值并将其用于重新创建CountDownTimer
var currentMillis: Long // <-- keep millisUntilFinished
// First creation of your timer
var timer = object : CountDownTimer(60000, 1000) {
override fun onTick(millisUntilFinished: Long) {
currentMillis = millisUntilFinished // <-- save value
textView3.text = (millisUntilFinished / 1000).toString() + ""
println("Timer : " + millisUntilFinished / 1000)
}
override fun onFinish() {}
}
}
...
// You start it
timer.start()
...
// For some reasons in your app you pause (really cancel) it
timer.cancel()
...
// And for reasuming
timer = object : CountDownTimer(currentMillis, 1000) {
override fun onTick(millisUntilFinished: Long) {
currentMillis = millisUntilFinished
textView3.text = (millisUntilFinished / 1000).toString() + ""
println("Timer : " + millisUntilFinished / 1000)
}
override fun onFinish() {}
}
}
答案 1 :(得分:0)
已经一年多了 我刚开始学习 Kotlin 我可以成功暂停和恢复功能,但调用 onFinish 函数有很大的延迟 我不是重新创建计时器对象,单击按钮时我调用 timer.cancel() 并将标志设置为 true 再次单击按钮时,我检查标志的值,如果为真,我调用 timer.start() 并将标志设置为 false