-
-
Save virendersran01/15ce3a484ea11816fa58db263f3a9852 to your computer and use it in GitHub Desktop.
TypeWriter animation effect in Android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment