【问题标题】:How to make a single TextView fade in and out with new text如何使用新文本使单个 TextView 淡入淡出
【发布时间】:2021-09-27 09:25:24
【问题描述】:

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

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

效果是将新文本淡入然后淡出。但是我尝试了很多不同的方法,但只能通过在 XML 和 Java 类中使用多个 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 对象重复淡入淡出(textViewAtextViewBtextViewC、@ 987654331@).

如何使用单个 TextView 实现这一点?

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

【问题讨论】:

    标签: java android xml animation


    【解决方案1】:

    要将单个 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++]);
    }
    

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-21
      • 2013-06-19
      • 1970-01-01
      • 2021-09-06
      相关资源
      最近更新 更多