问题
How is ObjectAnimator able to call the appropriate method setX
if the attribute x
is specified as a string? What I mean is, what technique is used to recognize that I want to animate the attribute rotation
of my view and call the appropriate method setRotation
of that view?
I've already understood how ObjectAnimator works and have managed to use it, it is quite simple, I am just curious about the operating principles.
回答1:
There are a number of ways to animate the rotation of a view:
1. ObjectAnimator.ofFloat(view, "rotation", 0f, 90f).start();
This uses reflection to call the setRotation(float f)
and float getRotation()
methods of the view.
You can use this method to animate any property of a class as long as that class has implemented the appropriate getter and setter methods for that property.
But reflection is a slow operation, so there is a second method that doesn't use reflection.
2. ObjectAnimator.ofFloat(view, View.ROTATION, 0f, 90f).start();
This uses the rotation Property of the view. Property is an abstract class that defines the setValue(T)
and the T get()
methods which in turn call the actual getter and setter of the supplied object. For example, the rotation property on the View
class uses the following code:
public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
@Override
public void setValue(View object, float value) {
object.setRotation(value);
}
@Override
public Float get(View object) {
return object.getRotation();
}
};
If you want to animate a custom property of an object, you can implement your own Property like the one above.
Then there is a third method, which also doesn't use reflection.
3. view.animate().rotation(90f);
This one has a fluent interface so it's easier to use. You can also chain multiple animations to run together, for example: view.animate().rotation(90f).translationX(10f);
The downside of this method is that you can only animate the standard properties of a View and not custom properties or properties on your own classes.
来源:https://stackoverflow.com/questions/28380891/how-does-android-objectanimator-recognize-the-attributes-setter-methods