gpt4 book ai didi

java - 在 TextView 中使用 TypeWriter 动画

转载 作者:行者123 更新时间:2023-12-02 09:15:48 26 4
gpt4 key购买 nike

我想在每次显示数组中的字符串时使用 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;
}
}
});

关于java - 在 TextView 中使用 TypeWriter 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59001068/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com