Skip to content Skip to sidebar Skip to footer

Using Float Value In Valueanimator Causes Exception

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

Solution 1:

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.

ValueAnimatoranimator= ValueAnimator.ofFloat(0f, 100.2f);
animator.addUpdateListener(newValueAnimator.AnimatorUpdateListener() {
            publicvoidonAnimationUpdate(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>() {
    @OverridepublicFloat 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:

DecimalFormatdf=newDecimalFormat("###.#");
df.setRoundingMode(RoundingMode.DOWN); //DOWN if you dont want number rounded, UP if you do want it roundedfloatoneDecimal= 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.

Solution 2:

Try this one may be this help you out. It works for me. Try to replace TypeEvaluator with TypeEvaluator

animator.setEvaluator(new TypeEvaluator<Float>() {
        @OverridepublicFloat evaluate(float fraction, Float startValue, Float endValue) {
            return (startValue + (endValue - startValue) * fraction);
        }
    });

Post a Comment for "Using Float Value In Valueanimator Causes Exception"