How does Android ObjectAnimator recognize the attributes setter methods?
Asked Answered
P

1

3

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.

Paranymph answered 7/2, 2015 at 10:12 Comment(1)
For property "foo" a method setFoo is called via reflactionRockhampton
E
11

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.

Eucalyptus answered 7/2, 2015 at 10:55 Comment(1)
Ugh, using reflection to animate Object sounds so bad, it should not even be possible !Disbelief

© 2022 - 2024 — McMap. All rights reserved.