Home > Software engineering >  Simple way to make animation character by character ( Kotlin )
Simple way to make animation character by character ( Kotlin )

Time:09-23

Show letter by letter in an easy way with kotlin Class Like : A An And Andr Andro Androi Android

CodePudding user response:

Try this:

val textView = TextView(this)
val resultText = "Android"
Thread {
    for (i in 0..resultText.length) {
        runOnUiThread { textView.text = resultText.substring(0, i) }
        Thread.sleep(500)
    }
}.start()

You'll have to add textView to some parent, like your contentView.

CodePudding user response:

I like Cactusroot's answer better but here's another way to do it with a Timer

private fun animateCharacters(activity: Activity, str: String, animationIntervalMs: Long) {
    val chars = str.toCharArray().toMutableList()
    var cStr = ""

    val timer = Timer()
    val task = object: TimerTask() {
        override fun run() {
            activity.runOnUiThread {
                val char = chars.removeFirstOrNull()
                if (char == null) {
                    cancel()
                    return@runOnUiThread
                }

                cStr  = char
                Log.i("Animated String", cStr)
                // update UI with new text
            }
        }
    }
    timer.schedule(task, 0, animationIntervalMs)
}
  • Related