我可以通过使用cancel()(timer.cancel())函数成功停止计时器。但是如何恢复呢?我搜索了很多代码,但所有内容都是Java。我在Kotlin需要它。你能给我建议吗?我使用代码:
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()
}
最佳答案
我的建议:保留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() {}
}
}