[英]Using TypeWriter animation in TextView
每次显示数组中的字符串时,我都想使用 TypeWriter 动画。
我使用 Texview 和 Button 一个接一个地显示它们:
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vibrator.vibrate(50);
txt.startAnimation(scale);
if(nextSentenceId < sentences.length){
txt.setText(sentences[nextSentenceId]);
++nextSentenceId;
}
}
});
我尝试使用我发现的 TypeWriter 类,这个类:
public class TypeWriterTextView extends TextView {
private CharSequence sequence;
private int mIndex;
private long delay = 150; //default is 150 milliseconds
public TypeWriterTextView(Context context) {
super(context);
}
public TypeWriterTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
@Override
public void run() {
setText(sequence.subSequence(0, mIndex++));
if (mIndex <= sequence.length()) {
handler.postDelayed(runnable, delay);
}
}
};
/**
* Display text with type writer animation
* @param txt content will be displayed
*/
public void displayTextWithAnimation(CharSequence txt) {
sequence = txt;
mIndex = 0;
setText("");
handler.removeCallbacks(runnable);
handler.postDelayed(runnable, delay);
}
/**
* Change the delay value with this method
* @param m
*/
public void setCharacterDelay(long m) {
delay = m;
} }
(代码来源: http : //www.devexchanges.info/2016/10/android-tip-type-writer-animation.html )
但我不知道如何在我的 OnClickListener 中使用它。 我想用它代替
txt.startAnimation(scale);
但是怎么样? 有没有办法为这种动画创建动画资源文件?
首先,确保布局文件中的View
是一个TypeWriterTextView
,而不仅仅是一个普通的TextView
。
接下来,Java 代码中的变量txt也必须是TypeWriterTextView
。
那么你应该可以使用打字机功能如下
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vibrator.vibrate(50);
// you said you don't want to use the scale animation any more
// txt.startAnimation(scale);
if(nextSentenceId < sentences.length){
// To get the String from the resource id,
// you need a Context. Since every View has one:
Context ctx = txt.getContext();
String sentence = ctx.getResources().getString(sentences[nextSentenceId]);
// Now pass the String (which is a kind of CharSequence)
// to the TypeWriterTextView method
txt.displayTextWithAnimation(sentence);
++nextSentenceId;
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.