in the timer I use how to add a time when a button is pressed? for example, I want millisUntilFinished to increase by 5 seconds when I press a button. I tried with the global variable but it didn't.
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()
As @TheWanderer answered you can not update the
millisUntilFinished
as there is no such method available in CountDownTimer class.To update the Timer you need to stop the current timer and start the new timer with updated millisInFuture value. Here is the sample code which will help you to achieve what you want.
You can't change the remaining time on an already-created CountDownTimer.
Looking at the source, both
millisInFuture
andcountDownInterval
are assigned to final variables; you can't change them.Now, the
mStopTimeInFuture
variable, the one the timer actually uses to stop, isn't final, and can be changed. But it's a private variable, meaning you'd need to use reflection, and it might not work properly.If you want a mutable CountDownTimer, you'll need to roll your own (easiest way would probably be to copy the CountDownTimer source and make the
mStopTimeInFuture
variable public and add milliseconds to it when needed).Here is a count down timer we use
And our use of a plain timer
Kotlin complains about this not sure why