Java – Android ObjectAnimator How does the Android ObjectAnimator identify property setting methods?

Android ObjectAnimator How does the Android ObjectAnimator identify property setting methods?… here is a solution to the problem.

Android ObjectAnimator How does the Android ObjectAnimator identify property setting methods?

If the property x is specified as a string, how can ObjectAnimator call the appropriate method setX? I mean, what technique is used to identify the appropriate method I want to animate for a View’s property rotation and call that view’s setRotation?

I’ve learned how ObjectAnimator works and used it successfully, it’s simple, I’m just curious about how it works.

Solution

There are many ways to animate the rotation of a View:

1. ObjectAnimator.ofFloat(view, "rotation", 0f, 90f).start();

This uses reflection to call the view's setRotation(float f) and float getRotation() methods.

As long as the class has implemented the appropriate getter and setter methods for the property, you can use this method to animate any property of the class.

But reflection is a

very slow operation, so there is a second way not to 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 setValue(T) and T get() methods, which call the actual getter and setter of the provided object. For example, the rotation property of 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 properties like above.

There is a third method, which also does not use reflection.

3. view.animate().rotation(90f);

This one has a smooth interface, so it’s easier to use. You can also link multiple animations to run together, for example: view.animate().rotation(90f).translationX(10f);

The disadvantage of this approach is that you can only animate standard properties of View, not custom properties or properties of your own classes.

Related Problems and Solutions