如何使单个 TextView 淡入和淡出新文本

How to make a single TextView fade in and out with new text

我正在尝试使用同一个 TextView 的单个实例来实现以下淡入淡出动画效果(通过设置 textView.setText):

  1. .setText 在初始化时设置为“欢迎”
  2. 淡出
  3. .setText 到“你好吗?”
  4. 淡入
  5. 淡出
  6. .setText 到“你多大了?”
  7. 淡入
  8. 淡出
  9. 等等...

效果是使新文本淡入然后淡出。但是我尝试了很多不同的方法,但只能通过在 XML 和 Java class.

中使用多个 TextView 对象来实现上述目的

这是我当前的代码:

textViewA.animate().alpha(1).setDuration(1000).setStartDelay(2000).withEndAction(new Runnable() {
            @Override
            public void run() {
                textViewA.animate().alpha(0).setDuration(1000).setStartDelay(2000).start();
                textViewB.setText("Next Question");

            }
        }).start();
    }

然后我必须不断重复上面的代码,通过将第二个 textViewB.setText 设置为新文本,然后为每个新的 textView 对象重复淡入淡出(textViewAtextViewB, textViewC, textViewD).

如何使用单个 TextView 实现此目的?

注意:我尝试简单地淡出textView,然后使用textView.setText,而alpha设置为0,然后淡入淡出 alpha 设置为 1,但只要我调用 textView.setText 方法,textView 就会覆盖推子并立即出现。

要将单个 TextView 用于淡入和淡出动画,您必须创建两个不同的 Runnable End Actions,一个用于 fadeInEndAction,一个用于 fadeOutEndAction 和从每个 Runnable 获取正确的 ViewPropertyAnimator 以开始淡入或淡出。

根据您的示例,您可以使用如下所示的单个 TextView 实现此效果:

TextView tv;
String[] stringMessages = {"Welcome", "How are you?", "How old are you?"};
int i = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);

    tv = findViewById(R.id.textView);
    setText();
    getFadeOutViewPropertyAnimator().start();
}

private ViewPropertyAnimator getFadeInViewPropertyAnimator(){
    return tv.animate().alpha(1).setDuration(1000).setStartDelay(2000).withEndAction(fadeInEndAction);
}

private ViewPropertyAnimator getFadeOutViewPropertyAnimator(){
    return tv.animate().alpha(0).setDuration(1000).setStartDelay(2000).withEndAction(fadeOutEndAction);
}

private final Runnable fadeInEndAction = new Runnable() {
    @Override
    public void run() {
        //no more strings to show stop the fade-in/out loop here
        if(i == stringMessages.length){
            return;
        }
        getFadeOutViewPropertyAnimator().start();
    }
};

private final Runnable fadeOutEndAction = new Runnable() {
    @Override
    public void run() {
        setText();
        getFadeInViewPropertyAnimator().start();
    }
};

private void setText(){
    tv.setText(stringMessages[i++]);
}

结果: