Piepants Piepants - 10 months ago 46
Android Question

Is there a way to use ValueAnimator with a starting point mid-way within the range?

I have image and I wish to animate its alpha in a repeating loop between transparent and visible. This is easy to do using ValueAnimator something like this:

mValueAnimator1 = ValueAnimator.ofFloat(1.0f, 0f);
mValueAnimator1.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
float value = ((Number) animation.getAnimatedValue()).floatValue();

That's straightforward if the starting alpha for the image should be 1, and it would also be straightforward if the starting alpha for the image should be 0.

But in my case I want the starting alpha to be some value within the range specified within ofFloat() i.e. if my starting alpha should be 0.75 then I want the animation to loop like this:

0.75, 0.85, 0.95, 1.0, 0.95, 0.75, 0.5, 0.3, 0.1, 0.0, 0.1, 0.2, 0.4, 0.6, 0.8 etc

(values are just representative to convey the general idea).

Is there a way of using ValueAnimator where the range is specified such as 0 - 1 but the starting point is mid way within that specified range?

Answer Source

You could use mValueAnimator1.setCurrentFraction(startingAlpha) to set the starting point, however setCurrentFraction() was only added in API 22.

Another approach might be to use an AnimatorSet consisting of two ValueAnimator objects, the first one with ofFloat(1.0f) (the value you want the animation to head to first), followed by another ValueAnimator that infinitely repeats between 1.0 and 0.0.