Using this post we can create a countdown timer in Android studio:
val timer = object: CountDownTimer(20000, 1000) {
override fun onTick(millisUntilFinished: Long) {...}
override fun onFinish() {...}
}
timer.start()
I want to change the background color if timer shows a number less than 10 and red for 9, green for 8, etc. My try is as follows for even and odd numbers:
override fun onTick(millisUntilFinished: Long) {
if (millisUntilFinished >10000) {
textView.setText("Remaining TIME:" millisUntilFinished / 1000)
}
else if(millisUntilFinished % 2000 == 0L) {
textView.setText("Remaining TIME:" millisUntilFinished / 1000)
textView.setBackgroundColor(0xFFf0000.toInt())
}
else {
textView.setText("Remaining TIME:" millisUntilFinished / 1000)
textView.setBackgroundColor(0xFF3F51B5.toInt())
}
}
}
But it only change the back color one time. Is there a way to access to the current time?
CodePudding user response:
This condition:
millisUntilFinished % 2000 == 0L
is only true if the millisUntilFinished
is an exact multiple of 2000. Given a device that's running at about 60fps on the UI thread, that gives you about a 1/17 chance of it being successful at changing it to red, and it will only stay red for 1/60th of a second.
I think your condition for the red state should be:
(millisUntilFinished / 1000) % 2 == 0L
We divide by 1000 first to get the number of whole seconds remaining, and then check if it's even.