在计时器中我使用如何在按下按钮时添加时间?例如,当按下按钮时,我希望millisUntilFinished增加5秒。我尝试使用全局变量,但事实并非如此。
object :CountDownTimer(10000,1000){
override fun onFinish() {
timeText.text = "Left : 0"
handler.removeCallbacks(runnable)
for (image in imageArray){
image.visibility = View.INVISIBLE
}
for (add in timeAdd){
add.visibility = View.INVISIBLE
}
button.visibility = View.VISIBLE
}
override fun onTick(millisUntilFinished: Long) {
timeText.text = "Left : "+millisUntilFinished/1000
}
}.start()
正如@TheWanderer回答你无法更新millisUntilFinished
,因为在CountDownTimer课程中没有这样的方法。
要更新Timer,您需要停止当前计时器并使用更新的millisInFuture值启动新计时器。以下示例代码可帮助您实现所需目标。
var timer: Timer?=null
//Call this method to start timer on activity start
private fun startTimer(){
timer = Timer(10000);
timer?.start()
}
//Call this method to update the timer
private fun updateTimer(){
if(timer!=null) {
val miliis = timer?.millisUntilFinished + TimeUnit.SECONDS.toMillis(5)
//Here you need to maintain single instance for previous
timer?.cancel()
timer = Timer(miliis);
timer?.start()
}else{
startTimer()
}
}
inner class Timer(miliis:Long) : CountDownTimer(miliis,1000){
var millisUntilFinished:Long = 0
override fun onFinish() {
timeText.text = "Left : 0"
handler.removeCallbacks(runnable)
for (image in imageArray){
image.visibility = View.INVISIBLE
}
for (add in timeAdd){
add.visibility = View.INVISIBLE
}
button.visibility = View.VISIBLE
}
override fun onTick(millisUntilFinished: Long) {
this.millisUntilFinished = millisUntilFinished
timeText.text = "Left : "+millisUntilFinished/1000
}
}
这是我们使用的倒计时器
fun message(msg:String){
object : CountDownTimer(4000, 1000) {
override fun onTick(millisUntilFinished: Long) {
tvMsg.visibility = View.VISIBLE
tvMsg.text = msg
}
override fun onFinish() {
tvMsg.visibility = View.INVISIBLE
tvMsg.text = ""
}
}.start()
}
而我们使用普通计时器
if (result) {
etItemData.setText("")
message("Record Removed")
Timer().schedule(1000){
thisACTIVITY()
}
科特林抱怨这不确定为什么
您无法更改已创建的CountDownTimer的剩余时间。
Looking at the source,millisInFuture
和countDownInterval
都被分配到最终变量;你无法改变它们。
现在,mStopTimeInFuture
变量,即计时器实际用于停止的变量,不是最终的,可以更改。但它是一个私有变量,意味着你需要使用反射,它可能无法正常工作。
如果你想要一个可变的CountDownTimer,你需要自己滚动(最简单的方法可能是复制CountDownTimer源并使mStopTimeInFuture
变量公开,并在需要时为它添加毫秒)。