ObjectAnimator

If we want to animate objects directly instead of properties, we could use the ObjectAnimator class. ObjectAnimator is a subclass of ValueAnimator and uses the same functionality and features, but adds the ability to animate objects properties by name.

For instance, to show how it works, we could animate a property of our own View this way. Let's add a small rotation to the whole canvas, controlled by the canvasAngle variable:

float canvasAngle; 
 
@Override 
protected void onDraw(Canvas canvas) { 
    canvas.save(); 
    canvas.rotate(canvasAngle, getWidth() / 2, getHeight() / 2); 
 
    ... 
 
    canvas.restore(); 
} 

We've got to create a setter and a getter with the right name: set<VariableName>and get<VariableName> in camel case, and in our specific case:

public void setCanvasAngle(float canvasAngle) { 
    this.canvasAngle = canvasAngle; 
} 
 
public float getCanvasAngle() { 
    return canvasAngle; 
} 

As these methods will be called by the ObjectAnimator, as we've already created them, we're ready to set up the ObjectAnimator itself:

ObjectAnimator canvasAngleAnimator = ObjectAnimator.ofFloat(this, "canvasAngle", -10.f, 10.f); 
canvasAngleAnimator.setDuration(3000); 
canvasAngleAnimator.setRepeatCount(ValueAnimator.INFINITE); 
canvasAngleAnimator.setRepeatMode(ValueAnimator.REVERSE); 
canvasAngleAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { 
    @Override 
    public void onAnimationUpdate(ValueAnimator animation) { 
        invalidate(); 
    } 
}); 

It is basically the same approach of the ValueAnimator, but in this case, we're specifying the property to animate using a String and the reference to the object. As we've just mentioned, ObjectAnimator will call the getter and setter of the property using the set<VariableName> and get<VariableName> format. In addition, in the onAnimationUpdate callback there is only a call to invalidate(). We've removed any value assignation like on the previous examples, as it'll be automatically updated by the ObjectAnimator.

You can find the whole example source code in the Example29-PropertyAnimation folder in the GitHub repository.