I am trying to animate the incrementing behaviour of a number from zero to a nth number. ValueAnimator works for an integer value but I attempted to this with a float value and it crashes with a ClassCastException
.
Exception:
java.lang.ClassCastException: java.lang.Float cannot be cast to java.lang.Integer
Code:
ValueAnimator animator = new ValueAnimator();
animator.setObjectValues(0, 100.2f);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
tvTotalAmount.setText("100.2");
}
});
animator.setEvaluator(new TypeEvaluator<Integer>() {
public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
return Math.round(startValue + (endValue - startValue) * fraction);
}
});
animator.setDuration(1500);
animator.start();
What changes do I need to do to make this work for float values? Thanks!
It seems to me you are misusing the ValueAnimator.
A much easier approach to using the Value Animator would be to use ValueAnimator.ofFloat(float... values)
this will automatically set the Evaluator for you. In your code you are supplying float values to an Integer Evaluator, causing your cast exception.
ValueAnimator animator = ValueAnimator.ofFloat(0f, 100.2f);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
tvTotalAmount.setText(String.valueOf((float)animation.getAnimatedValue()));
}
});
animator.setDuration(1500);
animator.start();
This code should work for your situation. I changed the update listener to set the text to whatever the animatedValue is so that your ValueAnimator actually does something. I do not see much point to setting the text to "100.2" every time the animator updates as the user would see no change, although you probably had other plans for the UpdateListener anyhow.
Alternatively, you could fix your Evaluator to evaluate Floats instead of Integers.
animator.setEvaluator(new TypeEvaluator<Float>() {
@Override
public Float evaluate(float fraction, Float startValue, Float endValue) {
return (startValue + (endValue - startValue) * fraction);
}
});
Truncating animatedValue
If you want to limit the increasing value to only 1 decimal place, I would suggest doing this:
DecimalFormat df = new DecimalFormat("###.#");
df.setRoundingMode(RoundingMode.DOWN); //DOWN if you dont want number rounded, UP if you do want it rounded
float oneDecimal = df.format((float)animation.getAnimatedValue());
Place this code within your onAnimationUpdate
listener and you can then receive a truncated value of the animated value to one decimal place.
Try this one may be this help you out. It works for me.
Try to replace TypeEvaluator with TypeEvaluator
animator.setEvaluator(new TypeEvaluator<Float>() {
@Override
public Float evaluate(float fraction, Float startValue, Float endValue) {
return (startValue + (endValue - startValue) * fraction);
}
});