Android Simple TextView Animation
Asked Answered
P

3

7

I've got a TextView that I would like to count down (3...2...1...stuff happens).

To make it a little more interesting, I want each digit to start at full opacity, and fade out to transparency.

Is there a simple way of doing this?

Pasargadae answered 31/1, 2012 at 2:26 Comment(0)
J
14

Try something like this:

 private void countDown(final TextView tv, final int count) {
   if (count == 0) { 
     tv.setText(""); //Note: the TextView will be visible again here.
     return;
   } 
   tv.setText(String.valueOf(count));
   AlphaAnimation animation = new AlphaAnimation(1.0f, 0.0f);
   animation.setDuration(1000);
   animation.setAnimationListener(new AnimationListener() {
     public void onAnimationEnd(Animation anim) {
       countDown(tv, count - 1);
     }
     ... //implement the other two methods
   });
   tv.startAnimation(animation);
 }

I just typed it out, so it might not compile as is.

Jacey answered 31/1, 2012 at 3:16 Comment(1)
replace tv.setText(count); with tv.setText(String.valueOf(count)); and code works fineSupervene
U
4

I've used a more conventional Android-style animation for this:

        ValueAnimator animator = new ValueAnimator();
        animator.setObjectValues(0, count);
        animator.addUpdateListener(new AnimatorUpdateListener() {
            public void onAnimationUpdate(ValueAnimator animation) {
                view.setText(String.valueOf(animation.getAnimatedValue()));
            }
        });
        animator.setEvaluator(new TypeEvaluator<Integer>() {
            public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
                return Math.round((endValue - startValue) * fraction);
            }
        });
        animator.setDuration(1000);
        animator.start();

You can play with the 0 and count values to make the counter go from any number to any number, and play with the 1000 to set the duration of the entire animation.

Note that this supports Android API level 11 and above, but you can use the awesome nineoldandroids project to make it backward compatible easily.

Uncivilized answered 24/6, 2014 at 14:26 Comment(0)
B
2

Take a look at CountDownAnimation.

I first tried @dmon solution, but since every animation starts at the end of the previous one you end up having a delay after several calls.

So, I implemented CountDownAnimation class which uses a Handler and the postDelayed function. By default, it uses the alpha animation, but you can set any animation. You can download the project here.

Burny answered 27/2, 2014 at 21:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.