Skip to content

Instantly share code, notes, and snippets.

@efimerdlerkravitz
Created February 22, 2018 12:40
Show Gist options
  • Save efimerdlerkravitz/3c224574819c80f98b7cd99a6317a873 to your computer and use it in GitHub Desktop.
Save efimerdlerkravitz/3c224574819c80f98b7cd99a6317a873 to your computer and use it in GitHub Desktop.
TypeWriter animation effect in Android
package com.example.uicomponents
import android.content.Context
import android.os.Handler
import android.util.AttributeSet
import android.widget.TextView
class TypeWriteTextView(context: Context?, attrs: AttributeSet?) : TextView(context, attrs) {
private var textList: List<String> = emptyList()
private var currentIndex: Int = 0
private var delay: Long = 150 // in ms
private val textHandler = Handler()
private var listener: (() -> Unit)? = null
private val characterAdder: Runnable = object : Runnable {
override fun run() {
text = textList.subList(0, currentIndex).joinToString(" ")
if (currentIndex < textList.size) {
currentIndex++
handler.postDelayed(this, delay)
} else {
listener?.invoke()
}
}
}
fun animateText(txt: CharSequence, endAnimationListener: (() -> Unit)? = null) {
textList = txt.split(Regex("\\s+"))
currentIndex = 0
listener = endAnimationListener
textHandler.removeCallbacks(characterAdder)
textHandler.postDelayed(characterAdder, delay)
}
fun setCharacterDelay(m: Long) {
delay = m
}
}
@efimerdlerkravitz
Copy link
Author

Based on https://medium.com/@ssaurel/create-a-type-writer-effect-on-android-4dc8f2ccada6
Couple of changes:

  • Instead of characters it works on words
  • You can set a listener that runs when the animation ends (in case you want to orchestrate animations)

@ssaurel
Copy link

ssaurel commented Feb 22, 2018

Great !

@ShreyanshJain2674
Copy link

where is dependency?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment