Android: Coroutines with Blinking TextView
I want to make a blinking text function. I found that can be easily done by Kotlin Coroutines and LifecycleOwner.
withTimeout
With Kotlin Coroutines, you can set a timer in one line.
val SEC = 1000L
withTimeout(duration * SEC) {
...
}
Well, you need to run it under a scope. In Android, I can choose LifecycleScope from LifecycleOwner.
Blink of TextView
To flash a TextView, you just need to make it VISIBLE and GONE.
repeat(31) { i ->
if (i%2 == 0)
errorTV.visibility = View.VISIBLE
else
errorTV.visibility = View.GONE
delay(300)
}
This block will blink 15 times.
Combination
fun flashError(
viewLifecycleOwner: LifecycleOwner,
errorTV: TextView,
duration: Long, // second
delay: Long, // ms
) {
val SEC = 1000L
viewLifecycleOwner.lifecycleScope.launch {
withTimeout(duration * SEC) {
repeat(31) { i ->
if (i%2 == 0)
errorTV.visibility = View.VISIBLE
else
errorTV.visibility = View.GONE
delay(delay)
}
}
}
}
This is a stand-alone function. I stored it in UiHelper.kt. I will use it to blink the error message in my app.
Test #1
To show an error about Email-Not-Found.
// Blink the error message
private fun showErrorMsg(message: String) {
customerEmailEt.requestFocus()
progressBar.visibility = View.GONE
emailNotFoundTV.text = message
flashError(
viewLifecycleOwner,
emailNotFoundTV,
10,
300
)
}
Let’s run.
It flashes 15 times.
Test #2
The app needs to show a Product-Not-Found error.
// Blink the error message
private fun showErrorMsg(message: String) {
productPB.visibility = View.GONE
productNotFoundTV.visibility = View.VISIBLE
productNotFoundTV.text = message
flashError(
viewLifecycleOwner,
productNotFoundTV,
10,
300
)
pidEt.requestFocus()
}
I have a blink ended cycles after 15 times.