Leon Li
Leon Li

Reputation: 1203

How to implement increasing number animation from 0 to 600 in 5 secs on TextVIew on android

I plan to implement integer number increase on textView from 0 to some value with animation within certain seconds. e.g show animation which increase number from 0 to 600 on textview for 5 seconds duration.

How can I implement this?

Upvotes: 41

Views: 27356

Answers (5)

Mr the cat
Mr the cat

Reputation: 115

I propose answer here for Kotlin developers :

 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()
}

Flexible extension in 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)

Upvotes: 7

Yasiru Nayanajith
Yasiru Nayanajith

Reputation: 1737

Use a 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();

Upvotes: 5

Frederik Schweiger
Frederik Schweiger

Reputation: 8742

You could use the ValueAnimator for that:

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

Upvotes: 123

Rafa0809
Rafa0809

Reputation: 1752

Take a look at this simple solution:

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

}

Upvotes: 14

Related Questions