在 TextView 中使用 TypeWriter 动画

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 class,这个 :

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);

但是怎么办?有没有办法为这种动画创建动画资源文件?

首先,确保布局文件中的 ViewTypeWriterTextView,而不是普通的 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;
        }
    }
});