3

I need to make some text (currently in a TextView) blink for a few seconds. There's several answers on how to do it in java here, but since Kotlin has some syntax/language features that java doesn't, I'm asking what is the most concise way you found to make text blink on Android using Kotlin.

While I'm aiming at making a fading/smooth blink, I'm open to approaches that would make a non smooth blink too.

Note that I'm also looking at lightweight code performance wise.

Thanks for your answers!

Louis CAD
  • 10,965
  • 2
  • 39
  • 58

1 Answers1

11

For a bit of fun, you can define an extension function:

fun View.blink(
    times: Int = Animation.INFINITE,
    duration: Long = 50L,
    offset: Long = 20L,
    minAlpha: Float = 0.0f,
    maxAlpha: Float = 1.0f,
    repeatMode: Int = Animation.REVERSE
) {
    startAnimation(AlphaAnimation(minAlpha, maxAlpha).also {
        it.duration = duration
        it.startOffset = offset
        it.repeatMode = repeatMode
        it.repeatCount = times
    })
}

And use it like so (using the example in the question you linked):

myText.blink(3)  // Blink 3 times
yourText.blink()  // Just keep blinking

Obviously you can change the parameters to suit your use case.

To stop the animation if needed, call clearAnimation() on the blinking view (yourText for the example above).

albodelu
  • 7,931
  • 7
  • 41
  • 84
Ruckus T-Boom
  • 4,566
  • 1
  • 28
  • 42