Skip to content

Instantly share code, notes, and snippets.

@Antarix
Last active March 4, 2021 06:12
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save Antarix/6388606 to your computer and use it in GitHub Desktop.
Save Antarix/6388606 to your computer and use it in GitHub Desktop.
TextView animation like type writer
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.TextView;
public class TypeWriter extends TextView {
private CharSequence mText;
private int mIndex;
private long mDelay = 150; //Default 150ms delay
public TypeWriter(Context context) {
super(context);
}
public TypeWriter(Context context, AttributeSet attrs) {
super(context, attrs);
}
private Handler mHandler = new Handler();
private Runnable characterAdder = new Runnable() {
@Override
public void run() {
setText(mText.subSequence(0, mIndex++));
if(mIndex <= mText.length()) {
mHandler.postDelayed(characterAdder, mDelay);
}
}
};
public void animateText(CharSequence text) {
mText = text;
mIndex = 0;
setText("");
mHandler.removeCallbacks(characterAdder);
mHandler.postDelayed(characterAdder, mDelay);
}
public void setCharacterDelay(long millis) {
mDelay = millis;
}
}
@claudijo
Copy link

Great example. Thanks! Shameless plug: For some ideas on how this could be extended with possibilities to also delete and pause animation of text, see https://gist.github.com/claudijo/0cf9f43705efadfeb852

@Antarix
Copy link
Author

Antarix commented Nov 3, 2017

Welcome @claudijo

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