user5864372
user5864372

Reputation:

ValueAnimator for count up effect on Android TextView

I am trying to make a cout-up effect in a TextView for a double value like this:

ValueAnimator animator = new  ValueAnimator();
animator.setObjectValues(0, 50.5); //double value
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    public void onAnimationUpdate(ValueAnimator animation) {
                textView.setText(String.valueOf(animation.getAnimatedValue()));
            }
        });
animator.setEvaluator(new TypeEvaluator<Double>() { // problem here
   @Override
   public Double evaluate(float fraction, Double startValue, Double endValue) {
      return  (startValue + (endValue - startValue) * fraction);
           }
        });
animator.setDuration(3000);
animator.start();// problem here

It gave me this: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double at the line animator.setEvaluator(new TypeEvaluator() at animator.start();

If I use the count up for a integer and implement The TypeEvaluator method, it works. Why not for a double?

Upvotes: 4

Views: 2279

Answers (2)

Satya Ambarish
Satya Ambarish

Reputation: 42

Here the ClassCastException occurred as the return type of evaluator is double.But some arithmetic operation is done in the return statement where the float (fraction) value is multiplied by double value (endValue - startValue) where the compiler gets confused as it does not know which value is going to be returned.Hence typecast the value of (endValue - startValue) * fraction to double.After modifications the code should look like

ValueAnimator animator = new  ValueAnimator();
    animator.setObjectValues(0d, 50.5d); //double value
    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    public void onAnimationUpdate(ValueAnimator animation) {
                textView.setText(String.valueOf(animation.getAnimatedValue()));
                }
            });
    animator.setEvaluator(new TypeEvaluator<Double>() { // problem here
       @Override
       public Double evaluate(float fraction, Double startValue, Double endValue) {
          return  (startValue + (double)((endValue - startValue) * fraction));
               }
            });
    animator.setDuration(3000);
    animator.start();

Upvotes: 3

prakash ubhadiya
prakash ubhadiya

Reputation: 1271

animator.setObjectValues(0, 50.5); in this line 0 consider as int value

change this line to

animator.setObjectValues(0d, 50.5d); //double value

Upvotes: 4

Related Questions