Android 带打字效果的自定义textview
以下是一个带打字效果的自定义TextView的示例代码:
public class TypingTextView extends AppCompatTextView {
private CharSequence mText;
private int mIndex;
private long mDelay = 50; // 打字延迟时间,单位毫秒
public TypingTextView(Context context) {
super(context);
}
public TypingTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TypingTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void animateText(CharSequence text) {
mText = text;
mIndex = 0;
setText("");
post(mRunnable);
}
private Runnable mRunnable = new Runnable() {
@Override
public void run() {
if (mIndex < mText.length()) {
setText(mText.subSequence(0, mIndex + 1));
mIndex++;
postDelayed(mRunnable, mDelay);
}
}
};
}
使用方法:
在布局文件中使用TypingTextView替换TextView,并在代码中调用animateText方法传入要打印的文本即可。
<com.example.TypingTextView
android:id="@+id/typing_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
TypingTextView typingTextView = findViewById(R.id.typing_text_view);
typingTextView.animateText("Hello, world!");
``
原文地址: https://www.cveoy.top/t/topic/fcql 著作权归作者所有。请勿转载和采集!