如何在android上的TextVIew上实现5秒内从0到600的数字递增动画

问题描述 投票:0回答:5

我计划在一定秒内通过动画实现 textView 上的整数从 0 增加到某个值。 例如,在文本视图上显示将数字从 0 增加到 600 的动画,持续 5 秒。

我该如何实现这个?

android animation textview
5个回答
121
投票

您可以使用 ValueAnimator 来实现:

private void startCountAnimation() {
    ValueAnimator animator = ValueAnimator.ofInt(0, 600);
    animator.setDuration(5000);
    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        public void onAnimationUpdate(ValueAnimator animation) {
            textView.setText(animation.getAnimatedValue().toString());
        }
    });
    animator.start();
}

14
投票

看看这个简单的解决方案

public void animateTextView(int initialValue, int finalValue, final TextView  textview) {
    ValueAnimator valueAnimator = ValueAnimator.ofInt(initialValue, finalValue);
    valueAnimator.setDuration(1500);
    valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
           textview.setText(valueAnimator.getAnimatedValue().toString());
        }
    });
    valueAnimator.start();

}

7
投票

我在这里为 Kotlin 开发者提出答案:

 fun startAnimation(textView: TextView) {
    val animator = ValueAnimator.ofInt(0, 600) 
    animator.duration = 5000 // 5 seconds
    animator.addUpdateListener { animation ->
        textView.text = animation.animatedValue.toString()
    }
    animator.start()
}

Kotlin 中的灵活扩展:

fun TextView.animateNumberChange(startingNumber: Int, endingNumber: Int, duration: Long = 500L) {
    val animator = ValueAnimator.ofInt(startingNumber, endingNumber)
    animator.duration = duration
    animator.addUpdateListener { animation ->
        this.text = animation.animatedValue.toString()
    }
    animator.interpolator = AccelerateDecelerateInterpolator()
    animator.start()
}

// usage:
myTextView.animateNumberChange(1, 10)

5
投票

使用 ValueAnimator

TextView textview = findViewById(R.id.textview1);

ValueAnimator valueAnimator = ValueAnimator.ofInt(0, 600);
valueAnimator.setDuration(5000);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
   @Override
   public void onAnimationUpdate(ValueAnimator valueAnimator) {
       textview.setText(valueAnimator.getAnimatedValue().toString());
   }
});
valueAnimator.start();

© www.soinside.com 2019 - 2024. All rights reserved.