24 กุมภาพันธ์ 2554
[This post is by Chet Haase, an Android engineer who specializes in graphics and animation, and who occasionally posts videos and articles on these topics on his CodeDependent blog at graphics-geek.blogspot.com. — Tim Bray]
One of the new features ushered in with the Honeycomb release is a new animation system, a set of APIs in a whole new package (android.animation
) that makes animating objects and properties much easier than it was before.
"But wait!" you blurt out, nearly projecting a mouthful of coffee onto your keyboard while reading this article, "Isn't there already an animation system in Android?"
Indeed, Android already has animation capabilities: there are several classes and lots of great functionality in the android.view.animation
package. For example, you can move, scale, rotate, and fade Views and combine multiple animations together in an AnimationSet
object to coordinate them. You can specify animations in a LayoutAnimationController
to get automatically staggered animation start times as a container lays out its child views. And you can use one of the many Interpolator
implementations like AccelerateInterpolator
and Bounce
to get natural, nonlinear timing behavior.
But there are a couple of major pieces of functionality lacking in the previous system.
For one thing, you can animate Views... and that's it. To a great extent, that's okay. The GUI objects in Android are, after all, Views. So as long as you want to move a Button, or a TextView, or a LinearLayout, or any other GUI object, the animations have you covered. But what if you have some custom drawing in your view that you'd like to animate, like the position of a Drawable, or the translucency of its background color? Then you're on your own, because the previous animation system only understands how to manipulate View objects.
The previous animations also have a limited scope: you can move, rotate, scale, and fade a View... and that's it. What about animating the background color of a View? Again, you're on your own, because the previous animations had a hard-coded set of things they were able to do, and you could not make them do anything else.
Finally, the previous animations changed the visual appearance of the target objects... but they didn't actually change the objects themselves. You may have run into this problem. Let's say you want to move a Button from one side of the screen to the other. You can use a TranslateAnimation
to do so, and the button will happily glide along to the other side of the screen. And when the animation is done, it will gladly snap back into its original location. So you find the setFillAfter(true)
method on Animation
and try it again. This time the button stays in place at the location to which it was animated. And you can verify that by clicking on it - Hey! How come the button isn't clicking? The problem is that the animation changes where the button is drawn, but not where the button physically exists within the container. If you want to click on the button, you'll have to click the location that it used to live in. Or, as a more effective solution (and one just a tad more useful to your users), you'll have to write your code to actually change the location of the button in the layout when the animation finishes.
It is for these reasons, among others, that we decided to offer a new animation system in Honeycomb, one built on the idea of "property animation."
The new animation system in Honeycomb is not specific to Views, is not limited to specific properties on objects, and is not just a visual animation system. Instead, it is a system that is all about animating values over time, and assigning those values to target objects and properties - any target objects and properties. So you can move a View or fade it in. And you can move a Drawable inside a View. And you can animate the background color of a Drawable. In fact, you can animate the values of any data structure; you just tell the animation system how long to run for, how to evaluate between values of a custom type, and what values to animate between, and the system handles the details of calculating the animated values and setting them on the target object.
Since the system is actually changing properties on target objects, the objects themselves are changed, not simply their appearance. So that button you move is actually moved, not just drawn in a different place. You can even click it in its animated location. Go ahead and click it; I dare you.
I'll walk briefly through some of the main classes at work in the new system, showing some sample code when appropriate. But for a more detailed view of how things work, check out the API Demos in the SDK for the new animations. There are many small applications written for the new Animations category (at the top of the list of demos in the application, right before the word App. I like working on animation because it usually comes first in the alphabet).
In fact, here's a quick video showing some of the animation code at work. The video starts off on the home screen of the device, where you can see some of the animation system at work in the transitions between screens. Then the video shows a sampling of some of the API Demos applications, to show the various kinds of things that the new animation system can do. This video was taken straight from the screen of a Honeycomb device, so this is what you should see on your system, once you install API Demos from the SDK.
Animator
Animator
is the superclass of the new animation classes, and has some of the common attributes and functionality of the subclasses. The subclasses are ValueAnimator
, which is the core timing engine of the system and which we'll see in the next section, and AnimatorSet
, which is used to choreograph multiple animators together into a single animation. You do not use Animator
directly, but some of the methods and properties of the subclasses are exposed at this superclass level, like the duration, startDelay and listener functionality.
The listeners tend to be important, because sometimes you want to key some action off of the end of an animation, such as removing a view after an animation fading it out is done. To listen for animator lifecycle events, implement the AnimatorListener
interface and add your listener to the Animator in question. For example, to perform an action when the animator ends, you could do this:
anim.addListener(new Animator.AnimatorListener() {
public void onAnimationStart(Animator animation) {}
public void onAnimationEnd(Animator animation) {
// do something when the animation is done
}
public void onAnimationCancel(Animator animation) {}
public void onAnimationRepeat(Animator animation) {}
});
As a convenience, there is an adapter class, AnimatorListenerAdapter
, that stubs out these methods so that you only need to override the one(s) that you care about:
anim.addListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation) {
// do something when the animation is done
}
});
ValueAnimator
ValueAnimator
is the main workhorse of the entire system. It runs the internal timing loop that causes all of a process's animations to calculate and set values and has all of the core functionality that allows it to do this, including the timing details of each animation, information about whether an animation repeats, listeners that receive update events, and the capability of evaluating different types of values (see TypeEvaluator
for more on this). There are two pieces to animating properties: calculating the animated values and setting those values on the object and property in question. ValueAnimator
takes care of the first part; calculating the values. The ObjectAnimator
class, which we'll see next, is responsible for setting those values on target objects.
Most of the time, you will want to use ObjectAnimator
, because it makes the whole process of animating values on target objects much easier. But sometimes you may want to use ValueAnimator
directly. For example, the object you want to animate may not expose setter functions necessary for the property animation system to work. Or perhaps you want to run a single animation and set several properties from that one animated value. Or maybe you just want a simple timing mechanism. Whatever the case, using ValueAnimator
is easy; you just set it up with the animation properties and values that you want and start it. For example, to animate values between 0 and 1 over a half-second, you could do this:
ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f);
anim.setDuration(500);
anim.start();
But animations are a bit like the tree in the forest philosophy question ("If a tree falls in the forest and nobody is there to hear it, does it make a sound?"). If you don't actually do anything with the values, does the animation run? Unlike the tree question, this one has an answer: of course it runs. But if you're not doing anything with the values, it might as well not be running. If you started it, chances are you want to do something with the values that it calculates along the way. So you add a listener to it, to listen for updates at each frame. And when you get the callback, you call getAnimatedValue()
, which returns an Object
, to find out what the current value is.
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
Float value = (Float) animation.getAnimatedValue();
// do something with value...
}
});
Of course, you don't necessarily always want to animate float
values. Maybe you need to animate something that's an integer instead:
ValueAnimator anim = ValueAnimator.ofInt(0, 100);
or in XML:
<animator xmlns:android="http://schemas.android.com/apk/res/android"
android:valueFrom="0"
android:valueTo="100"
android:valueType="intType"/>
In fact, maybe you need to animate something entirely different, like a Point
, or a Rect
, or some custom data structure of your own. The only types that the animation system understands by default are float
and int
, but that doesn't mean that you're stuck with those two types. You can to use the Object
version of the factory method, along with a TypeEvaluator
(explained later), to tell the system how to calculate animated values for this unknown type:
Point p0 = new Point(0, 0);
Point p1 = new Point(100, 200);
ValueAnimator anim = ValueAnimator.ofObject(pointEvaluator, p0, p1);
There are other animation attributes that you can set on a ValueAnimator
besides duration, including:
setStartDelay(long)
: This property controls how long the animation waits after a call to start()
before it starts playing.setRepeatCount(int)
and setRepeatMode(int)
: These functions control how many times the animation repeats and whether it repeats in a loop or reverses direction each time.setInterpolator(TimeInterpolator)
: This object controls the timing behavior of the animation. By default, animations accelerate into and decelerate out of the motion, but you can change that behavior by setting a different interpolator. This function acts just like the one of the same name in the previous Animation
class; it's just that the type of the parameter (TimeInterpolator
) is different from that of the previous version (Interpolator
). But the TimeInterpolator
interface is just a super-interface of the existing Interpolator
interface in the android.view.animation
package, so you can use any of the existing Interpolator
implementations, like Bounce
, as arguments to this function on ValueAnimator
.ObjectAnimator
ObjectAnimator
is probably the main class that you will use in the new animation system. You use it to construct animations with the timing and values that ValueAnimator
takes, and also give it a target object and property name to animate. It then quietly animates the value and sets those animated values on the specified object/property. For example, to fade out some object myObject
, we could animate the alpha
property like this:
ObjectAnimator.ofFloat(myObject, "alpha", 0f).start();
Note, in this example, a special feature that you can use to make your animations more succinct; you can tell it the value to animate to, and it will use the current value of the property as the starting value. In this case, the animation will start from whatever value alpha
has now and will end up at 0.
You could create the same thing in an XML resource as follows:
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:valueTo="0"
android:propertyName="alpha"/>
Note, in the XML version, that you cannot set the target object; this must be done in code after the resource is loaded:
ObjectAnimator anim = AnimatorInflator.loadAnimator(context, resID);
anim.setTarget(myObject);
anim.start();
There is a hidden assumption here about properties and getter/setter functions that you have to understand before using ObjectAnimator: you must have a public "set" function on your object that corresponds to the property name and takes the appropriate type. Also, if you use only one value, as in the example above, your are asking the animation system to derive the starting value from the object, so you must also have a public "get" function which returns the appropriate type. For example, the class of myObject
in the code above must have these two public functions in order for the animation to succeed:
public void setAlpha(float value);
public float getAlpha();
So by passing in a target object of some type and the name of some property foo
supposedly on that object, you are implicitly declaring a contract that that object has at least a setFoo()
function and possibly also a getFoo()
function, both of which handle the type used in the animation declaration. If all of this is true, then the animation will be able to find those setter/getter functions on the object and set values during the animation. If the functions do not exist, then the animation will fail at runtime, since it will be unable to locate the functions it needs. (Note to users of ProGuard, or other code-stripping utilities: If your setter/getter functions are not used anywhere else in the code, make sure you tell the utility to leave the functions there, because otherwise they may get stripped out. The binding during animation creation is very loose and these utilities have no way of knowing that these functions will be required at runtime.)
The observant reader, or at least the ones that have not yet browsed on to some other article, may have pinpointed a flaw in the system thus far. If the new animation framework revolves around animating properties, and if animations will be used to animate, to a large extent, View objects, then how can they be used against the View class, which exposes none of its properties through set/get functions?
Excellent question: you get to advance to the bonus round and keep reading.
The way it works is that we added new properties to the View class in Honeycomb. The old animation system transformed and faded View objects by just changing the way that they were drawn. This was actually functionality handled in the container of each View, because the View itself had no transform properties to manipulate. But now it does: we've added several properties to View to make it possible to animate Views directly, allowing you to not only transform the way a View looks, but to transform its actual location and orientation. Here are the new properties in View that you can set, get and animate directly:
translationX
and translationY
: These properties control where the View is located as a delta from its left
and top
coordinates which are set by its layout container. You can run a move animation on a button by animating these, like this: ObjectAnimator.ofFloat(view, "translationX", 0f, 100f);
.rotation
, rotationX
, and rotationY
: These properties control the rotation in 2D (rotation
) and 3D around the pivot point.scaleX
and scaleY
: These properties control the 2D scaling of a View around its pivot point.pivotX
and pivotY
: These properties control the location of the pivot point, around which the rotation and scaling transforms occur. By default, the pivot point is centered at the center of the object.x
and y
: These are simple utility properties to describe the final location of the View in its container, as a sum of the left/top and translationX/translationY values.alpha
: This is my personal favorite property. No longer is it necessary to fade out an object by changing a value on its transform (a process which just didn't seem right). Instead, there is an actual alpha
value on the View itself. This value is 1 (opaque) by default, with a value of 0 representing full transparency (i.e., it won't be visible). To fade a View out, you can do this: ObjectAnimator.ofFloat(view, "alpha", 0f);
Note that all of the "properties" described above are actually available in the form of set/get functions (e.g., setRotation()
and getRotation()
for the rotation
property). This makes them both possible to access from the animation system and (probably more importantly) likely to do the right thing when changed. That is, you don't want to scale an object and have it just sit there because the system didn't know that it needed to redraw the object in its new orientation; each of the setter functions takes care to run the appropriate invalidation step to make the rendering work correctly.
AnimatorSet
This class, like the previous AnimationSet
, exists to make it easier to choreograph multiple animations. Suppose you want several animations running in tandem, like you want to fade out several views, then slide in other ones while fading them in. You could do all of this with separate animations and either manually starting the animations at the right times or with startDelay
s set on the various delayed animations. Or you could use AnimatorSet
to do all of that for you. AnimatorSet
allows you to animations that play together, playTogether(Animator...)
, animations that play one after the other, playSequentially(Animator...)
, or you can organically build up a set of animations that play together, sequentially, or with specified delays by calling the functions in the AnimatorSet.Builder
class, with()
, before()
, and after()
. For example, to fade out v1 and then slide in v2 while fading it, you could do something like this:
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(v1, "alpha", 0f);
ObjectAnimator mover = ObjectAnimator.ofFloat(v2, "translationX", -500f, 0f);
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(v2, "alpha", 0f, 1f);
AnimatorSet animSet = new AnimatorSet().play(mover).with(fadeIn).after(fadeOut);;
animSet.start();
Like ValueAnimator
and ObjectAnimator
, you can create AnimatorSet
objects in XML resources as well.
TypeEvaluator
I wanted to talk about just one more thing, and then I'll leave you alone to explore the code and play with the API demos. The last class I wanted to mention is TypeEvaluator
. You may not use this class directly for most of your animations, but you should that it's there in case you need it. As I said earlier, the system knows how to animate float
and int
values, but otherwise it needs some help knowing how to interpolate between the values you give it. For example, if you want to animate between the Point
values in one of the examples above, how is the system supposed to know how to interpolate the values between the start and end points? Here's the answer: you tell it how to interpolate, using TypeEvaluator
.
TypeEvaluator
is a simple interface that you implement that the system calls on each frame to help it calculate an animated value. It takes a floating point value which represents the current elapsed fraction of the animation and the start and end values that you supplied when you created the animation and it returns the interpolated value between those two values at that fraction. For example, here's the built-in FloatEvaluator
class used to calculate animated floating point values:
public class FloatEvaluator implements TypeEvaluator {
public Object evaluate(float fraction, Object startValue, Object endValue) {
float startFloat = ((Number) startValue).floatValue();
return startFloat + fraction * (((Number) endValue).floatValue() - startFloat);
}
}
But how does it work with a more complex type? For an example of that, here is an implementation of an evaluator for the Point
class, from our earlier example:
public class PointEvaluator implements TypeEvaluator {
public Object evaluate(float fraction, Object startValue, Object endValue) {
Point startPoint = (Point) startValue;
Point endPoint = (Point) endValue;
return new Point(startPoint.x + fraction * (endPoint.x - startPoint.x),
startPoint.y + fraction * (endPoint.y - startPoint.y));
}
}
Basically, this evaluator (and probably any evaluator you would write) is just doing a simple linear interpolation between two values. In this case, each 'value' consists of two sub-values, so it is linearly interpolating between each of those.
You tell the animation system to use your evaluator by either calling the setEvaluator()
method on ValueAnimator
or by supplying it as an argument in the Object version of the factory method. To continue our earlier example animating Point
values, you could use our new PointEvaluator
class above to complete that code:
Point p0 = new Point(0, 0);
Point p1 = new Point(100, 200);
ValueAnimator anim = ValueAnimator.ofObject(new PointEvaluator(), p0, p1);
One of the ways that you might use this interface is through the ArgbEvaluator
implementation, which is included in the Android SDK. If you animate a color property, you will probably either use this evaluator automatically (which is the case if you create an animator in an XML resource and supply colors as values) or you can set it manually on the animator as described in the previous section.
There's so much more to the new animation system that I haven't gotten to. There's the repetition functionality, the listeners for animation lifecycle events, the ability to supply multiple values to the factory methods to get animations between more than just two endpoints, the ability to use the Keyframe
class to specify a more complex time/value sequence, the use of PropertyValuesHolder
to specify multiple properties to animate in parallel, the LayoutTransition
class for automating simple layout animations, and so many other things. But I really have to stop writing soon and get back to working on the code. I'll try to post more articles in the future on some of these items, but also keep an eye on my blog at graphics-geek.blogspot.com for upcoming articles, tutorials, and videos on this and related topics. Until then, check out the API demos, read the overview of Property Animation posted with the 3.0 SDK, dive into the code, and just play with it.