4

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?

2 Answers2

4

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

change this line to

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

prakash ubhadiya
  • 1,242
  • 1
  • 12
  • 24
  • that did the trick, thanks, I wasn't paying attention to the 0 value! –  Sep 14 '16 at 09:23
3

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();
Rissmon Suresh
  • 13,173
  • 5
  • 29
  • 38
  • adding (double) in front of (endValue - startValue) * fraction is redundant because the inspection reports a double value –  Sep 14 '16 at 09:25
  • cast the product to double like (double)((endValue - startValue) * fraction) – Satya Ambarish Sep 14 '16 at 09:27
  • It's the same thing, still redundant, the problem was that I forgot to put "d" after 0 at setObjectValues. –  Sep 14 '16 at 09:31