0

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?

C.F.G
  • 817
  • 8
  • 16
  • 1
    You could try to invalidate the textView after changing the background color using textView.invalidate() - note that this will refresh the view every time it's called so it might not be the most efficient way of going about it. – Robin Sep 27 '22 at 13:45

1 Answers1

1

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.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
  • That's worked surprisingly! That is weird a bit. How you derived that calcs about 1/17? – C.F.G Sep 27 '22 at 15:10
  • 1
    A frame at 60fps is 17ms long, so the chances of aligning with an exact multiple of 2000 on the frame that is closest to a multiple of 2000 is 1 out of 17. But I should have said that it only appears red for 1/60 of a second. – Tenfour04 Sep 27 '22 at 15:15