Continuously animate Text from left to right

后端 未结 3 969
温柔的废话
温柔的废话 2021-02-06 16:14

I\'m trying to create an animation which moves a TextView from left to right and loop indefinitely. This is the TextView I want to animate:

<         


        
3条回答
  •  北恋
    北恋 (楼主)
    2021-02-06 16:16

    What you want to do can be easily achieved with a simple ValueAnimator.

    What you first have to do is put two identical versions of the TextView you want to animate into your layout. In this example my layout looks like this:

    
    
    
        
    
        
    
    
    

    Then - as I already mentioned - you use a ValueAnimator to animate the translationX property of both Views, but offset one by the width of the screen (since the TextViews above use match_parent as width their width is equal to the width of the screen and that is what I will be using to offset the position of one of them). Your code should look something like this:

    final TextView first = (TextView) findViewById(R.id.first);
    final TextView second = (TextView) findViewById(R.id.second);
    
    final ValueAnimator animator = ValueAnimator.ofFloat(0.0f, 1.0f);
    animator.setRepeatCount(ValueAnimator.INFINITE);
    animator.setInterpolator(new LinearInterpolator());
    animator.setDuration(9000L);
    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            final float progress = (float) animation.getAnimatedValue();
            final float width = first.getWidth();
            final float translationX = width * progress;
            first.setTranslationX(translationX);
            second.setTranslationX(translationX - width);
        }
    });
    animator.start();
    

    And the result should look something like this:

提交回复
热议问题