- Animation and Animator
- Using the Object Animator
- Simplifying View Animation with ViewPropertyAnimator
- Animating Layout Changes
- Conclusion
Using the Object Animator
So let’s take a closer look at what the Animator package can do. The easiest way to animate a property on an object is to use the ObjectAnimator class (android.animation.ObjectAnimator). Let's show this by example:
ObjectAnimator.ofInt(sampleButton, "left", 100, 250) .setDuration(250) .start();
This snippet of code tells the animation system to animate the 'left' value of sampleButton from 100 to 250 over a 250 milliseconds of time.
You can easily animate other property values at the same time. You can also easily animate to multiple values on a single property. For instance, where sampleButton is an instance of Button:
ObjectAnimator.ofFloat(sampleButton, "alpha", 0.5f, 1f, 0f) .setDuration(2500) .start();
This will modify the opacity of the Button view object. The Button will start it at an alpha value of 50%, then become completely opaque before fading out until it's completely transparent. This animation will take place over the course of 2500ms, or 2.5 seconds.
Internally, the Animator package uses Java reflection to get at the property value of the object. This is important to be aware of, because reflection does affect performance. The inefficiencies of this side effect can add up if you're animating lots of properties on lots of different view objects. But, this feature is also what allows the Animator package to provide animation capabilities to any object.
This flexibility is a benefit worth considering. Take the following class implementation, called CustomTest:
class CustomTest { private static final String LOG_TAG = "CustomTest"; private int val; public int getVal() { Log.v(LOG_TAG, "getVal()="+val); return val; } public void setVal(int val) { Log.v(LOG_TAG, "setVal("+val+")"); this.val = val; } }
All the CustomTest class does is handle a single property with the appropriate getters and setters. Using the ObjectAnimator class, we can "animate" the "val" property:
ObjectAnimator.ofInt(new CustomTest(), "val", 15) .setDuration(1000) .start();
This code will create lengthy LogCat output that starts with a single "getVal()=0" and ends with a single "setVal(15)"in between, each of the other values is set multiple times, depending on how busy the rest of the system is. This shows how the ObjectAnimator object is querying for the initial property value before animating to the new property value. It also shows how the calls may be made multiple times. Try it. This example class can help give you an idea of how the ObjectAnimator works with any classeven your own custom classes.
Consider this: Because it can work on any object, you can use this class to perform animation using any graphics systemeven when using OpenGL. It may not be the most efficient for your particular use case, but it's very fast and easy to add to your code.