Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a count-up effect for a textView in Android

Tags:

I am working on an app that counts the number of questions marks in a few paragraphs of text.

After the scanning is done (which takes no time at all) I would love to have the total presented after the number goes from 0 to TOTAL. So, for 10: 0,1,2,3,4,5,6,7,8,9 10 and then STOP.

I have tried a couple of different techniques:

                TextView sentScore = (TextView) findViewById(R.id.sentScore);

                long freezeTime = SystemClock.uptimeMillis();

                for (int i = 0; i < sent; i++) {
                    if ((SystemClock.uptimeMillis() - freezeTime) > 500) {
                        sentScore.setText(sent.toString());
                    }
                }

Also I tried this:

    for (int i = 0; i < sent; i++) { 
        // try {
            Thread.sleep(500);

        } catch (InterruptedException ie) {
            sentScore.setText(i.toString()); 
        } 
    }

I am sure these are both completely amateur attempts. Any help would be much-appreciated.

Thanks,

Richard

like image 485
Richard Burton Avatar asked Mar 16 '12 12:03

Richard Burton


1 Answers

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(startValue + (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.

like image 122
marmor Avatar answered Sep 21 '22 07:09

marmor