ValueAnimator.java revision 608fc3cbed6062f29cd512c08aacb8c1632a8851
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.animation;
18
19import android.os.Handler;
20import android.os.Looper;
21import android.os.Message;
22import android.view.animation.AccelerateDecelerateInterpolator;
23import android.view.animation.AnimationUtils;
24
25import java.util.ArrayList;
26import java.util.HashMap;
27
28/**
29 * This class provides a simple timing engine for running animations
30 * which calculate animated values and set them on target objects.
31 *
32 * <p>There is a single timing pulse that all animations use. It runs in a
33 * custom handler to ensure that property changes happen on the UI thread.</p>
34 *
35 * <p>By default, ValueAnimator uses non-linear time interpolation, via the
36 * {@link AccelerateDecelerateInterpolator} class, which accelerates into and decelerates
37 * out of an animation. This behavior can be changed by calling
38 * {@link ValueAnimator#setInterpolator(TimeInterpolator)}.</p>
39 */
40public class ValueAnimator<T> extends Animator {
41
42    /**
43     * Internal constants
44     */
45
46    /*
47     * The default amount of time in ms between animation frames
48     */
49    private static final long DEFAULT_FRAME_DELAY = 10;
50
51    /**
52     * Messages sent to timing handler: START is sent when an animation first begins, FRAME is sent
53     * by the handler to itself to process the next animation frame
54     */
55    private static final int ANIMATION_START = 0;
56    private static final int ANIMATION_FRAME = 1;
57
58    /**
59     * Values used with internal variable mPlayingState to indicate the current state of an
60     * animation.
61     */
62    private static final int STOPPED    = 0; // Not yet playing
63    private static final int RUNNING    = 1; // Playing normally
64    private static final int CANCELED   = 2; // cancel() called - need to end it
65    private static final int ENDED      = 3; // end() called - need to end it
66    private static final int SEEKED     = 4; // Seeked to some time value
67
68    /**
69     * Internal variables
70     * NOTE: This object implements the clone() method, making a deep copy of any referenced
71     * objects. As other non-trivial fields are added to this class, make sure to add logic
72     * to clone() to make deep copies of them.
73     */
74
75    // The first time that the animation's animateFrame() method is called. This time is used to
76    // determine elapsed time (and therefore the elapsed fraction) in subsequent calls
77    // to animateFrame()
78    private long mStartTime;
79
80    /**
81     * Set when setCurrentPlayTime() is called. If negative, animation is not currently seeked
82     * to a value.
83     */
84    private long mSeekTime = -1;
85
86    // The static sAnimationHandler processes the internal timing loop on which all animations
87    // are based
88    private static AnimationHandler sAnimationHandler;
89
90    // The static list of all active animations
91    private static final ArrayList<ValueAnimator> sAnimations = new ArrayList<ValueAnimator>();
92
93    // The set of animations to be started on the next animation frame
94    private static final ArrayList<ValueAnimator> sPendingAnimations = new ArrayList<ValueAnimator>();
95
96    // The time interpolator to be used if none is set on the animation
97    private static final TimeInterpolator sDefaultInterpolator =
98            new AccelerateDecelerateInterpolator();
99
100    // type evaluators for the three primitive types handled by this implementation
101    private static final TypeEvaluator sIntEvaluator = new IntEvaluator();
102    private static final TypeEvaluator sFloatEvaluator = new FloatEvaluator();
103    private static final TypeEvaluator sDoubleEvaluator = new DoubleEvaluator();
104
105    /**
106     * Used to indicate whether the animation is currently playing in reverse. This causes the
107     * elapsed fraction to be inverted to calculate the appropriate values.
108     */
109    private boolean mPlayingBackwards = false;
110
111    /**
112     * This variable tracks the current iteration that is playing. When mCurrentIteration exceeds the
113     * repeatCount (if repeatCount!=INFINITE), the animation ends
114     */
115    private int mCurrentIteration = 0;
116
117    /**
118     * Tracks whether a startDelay'd animation has begun playing through the startDelay.
119     */
120    private boolean mStartedDelay = false;
121
122    /**
123     * Tracks the time at which the animation began playing through its startDelay. This is
124     * different from the mStartTime variable, which is used to track when the animation became
125     * active (which is when the startDelay expired and the animation was added to the active
126     * animations list).
127     */
128    private long mDelayStartTime;
129
130    /**
131     * Flag that represents the current state of the animation. Used to figure out when to start
132     * an animation (if state == STOPPED). Also used to end an animation that
133     * has been cancel()'d or end()'d since the last animation frame. Possible values are
134     * STOPPED, RUNNING, ENDED, CANCELED.
135     */
136    private int mPlayingState = STOPPED;
137
138    /**
139     * Internal collections used to avoid set collisions as animations start and end while being
140     * processed.
141     */
142    private static final ArrayList<ValueAnimator> sEndingAnims = new ArrayList<ValueAnimator>();
143    private static final ArrayList<ValueAnimator> sDelayedAnims = new ArrayList<ValueAnimator>();
144    private static final ArrayList<ValueAnimator> sReadyAnims = new ArrayList<ValueAnimator>();
145
146    /**
147     * Flag that denotes whether the animation is set up and ready to go. Used to
148     * set up animation that has not yet been started.
149     */
150    boolean mInitialized = false;
151
152    //
153    // Backing variables
154    //
155
156    // How long the animation should last in ms
157    private long mDuration;
158
159    // The amount of time in ms to delay starting the animation after start() is called
160    private long mStartDelay = 0;
161
162    // The number of milliseconds between animation frames
163    private static long sFrameDelay = DEFAULT_FRAME_DELAY;
164
165    // The number of times the animation will repeat. The default is 0, which means the animation
166    // will play only once
167    private int mRepeatCount = 0;
168
169    /**
170     * The type of repetition that will occur when repeatMode is nonzero. RESTART means the
171     * animation will start from the beginning on every new cycle. REVERSE means the animation
172     * will reverse directions on each iteration.
173     */
174    private int mRepeatMode = RESTART;
175
176    /**
177     * The time interpolator to be used. The elapsed fraction of the animation will be passed
178     * through this interpolator to calculate the interpolated fraction, which is then used to
179     * calculate the animated values.
180     */
181    private TimeInterpolator mInterpolator = sDefaultInterpolator;
182
183    /**
184     * The set of listeners to be sent events through the life of an animation.
185     */
186    private ArrayList<AnimatorUpdateListener> mUpdateListeners = null;
187
188    /**
189     * The property/value sets being animated.
190     */
191    PropertyValuesHolder[] mValues;
192
193    /**
194     * A hashmap of the PropertyValuesHolder objects. This map is used to lookup animated values
195     * by property name during calls to getAnimatedValue(String).
196     */
197    HashMap<String, PropertyValuesHolder> mValuesMap;
198
199    /**
200     * Public constants
201     */
202
203    /**
204     * When the animation reaches the end and <code>repeatCount</code> is INFINITE
205     * or a positive value, the animation restarts from the beginning.
206     */
207    public static final int RESTART = 1;
208    /**
209     * When the animation reaches the end and <code>repeatCount</code> is INFINITE
210     * or a positive value, the animation reverses direction on every iteration.
211     */
212    public static final int REVERSE = 2;
213    /**
214     * This value used used with the {@link #setRepeatCount(int)} property to repeat
215     * the animation indefinitely.
216     */
217    public static final int INFINITE = -1;
218
219    /**
220     * Creates a new ValueAnimator object. This default constructor is primarily for
221     * use internally; the other constructors which take parameters are more generally
222     * useful.
223     */
224    public ValueAnimator() {
225    }
226
227    /**
228     * Constructs an ValueAnimator object with the specified duration and set of
229     * values. If the values are a set of PropertyValuesHolder objects, then these objects
230     * define the potentially multiple properties being animated and the values the properties are
231     * animated between. Otherwise, the values define a single set of values animated between.
232     *
233     * @param duration The length of the animation, in milliseconds.
234     * @param values The set of values to animate between. If these values are not
235     * PropertyValuesHolder objects, then there should be more than one value, since the values
236     * determine the interval to animate between.
237     */
238    public ValueAnimator(long duration, T...values) {
239        mDuration = duration;
240        if (values.length > 0) {
241            setValues(values);
242        }
243    }
244
245    /**
246     * Sets the values, per property, being animated between. This function is called internally
247     * by the constructors of ValueAnimator that take a list of values. But an ValueAnimator can
248     * be constructed without values and this method can be called to set the values manually
249     * instead.
250     *
251     * @param values The set of values, per property, being animated between.
252     */
253    public void setValues(PropertyValuesHolder... values) {
254        int numValues = values.length;
255        mValues = values;
256        mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues);
257        for (int i = 0; i < numValues; ++i) {
258            PropertyValuesHolder valuesHolder = (PropertyValuesHolder) values[i];
259            mValuesMap.put(valuesHolder.getPropertyName(), valuesHolder);
260        }
261        // New property/values/target should cause re-initialization prior to starting
262        mInitialized = false;
263    }
264
265    /**
266     * Returns the values that this ValueAnimator animates between. These values are stored in
267     * PropertyValuesHolder objects, even if the ValueAnimator was created with a simple list
268     * of value objects instead.
269     *
270     * @return PropertyValuesHolder[] An array of PropertyValuesHolder objects which hold the
271     * values, per property, that define the animation.
272     */
273    public PropertyValuesHolder[] getValues() {
274        return mValues;
275    }
276
277    /**
278     * Sets the values to animate between for this animation. If <code>values</code> is
279     * a set of PropertyValuesHolder objects, these objects will become the set of properties
280     * animated and the values that those properties are animated between. Otherwise, this method
281     * will set only one set of values for the ValueAnimator. Also, if the values are not
282     * PropertyValuesHolder objects and if there are already multiple sets of
283     * values defined for this ValueAnimator via
284     * more than one PropertyValuesHolder objects, this method will set the values for
285     * the first of those objects.
286     *
287     * @param values The set of values to animate between.
288     */
289    public void setValues(T... values) {
290        if (mValues == null || mValues.length == 0) {
291            setValues(new PropertyValuesHolder[]{
292                    new PropertyValuesHolder("", (Object[])values)});
293        } else {
294            PropertyValuesHolder valuesHolder = mValues[0];
295            valuesHolder.setValues(values);
296        }
297        // New property/values/target should cause re-initialization prior to starting
298        mInitialized = false;
299    }
300
301    /**
302     * This function is called immediately before processing the first animation
303     * frame of an animation. If there is a nonzero <code>startDelay</code>, the
304     * function is called after that delay ends.
305     * It takes care of the final initialization steps for the
306     * animation.
307     *
308     *  <p>Overrides of this method should call the superclass method to ensure
309     *  that internal mechanisms for the animation are set up correctly.</p>
310     */
311    void initAnimation() {
312        if (!mInitialized) {
313            int numValues = mValues.length;
314            for (int i = 0; i < numValues; ++i) {
315                mValues[i].init();
316            }
317            mCurrentIteration = 0;
318            mInitialized = true;
319        }
320    }
321
322
323    /**
324     * Sets the length of the animation.
325     *
326     * @param duration The length of the animation, in milliseconds.
327     */
328    public void setDuration(long duration) {
329        mDuration = duration;
330    }
331
332    /**
333     * Gets the length of the animation.
334     *
335     * @return The length of the animation, in milliseconds.
336     */
337    public long getDuration() {
338        return mDuration;
339    }
340
341    /**
342     * Sets the position of the animation to the specified point in time. This time should
343     * be between 0 and the total duration of the animation, including any repetition. If
344     * the animation has not yet been started, then it will not advance forward after it is
345     * set to this time; it will simply set the time to this value and perform any appropriate
346     * actions based on that time. If the animation is already running, then setCurrentPlayTime()
347     * will set the current playing time to this value and continue playing from that point.
348     *
349     * @param playTime The time, in milliseconds, to which the animation is advanced or rewound.
350     */
351    public void setCurrentPlayTime(long playTime) {
352        initAnimation();
353        long currentTime = AnimationUtils.currentAnimationTimeMillis();
354        if (mPlayingState != RUNNING) {
355            mSeekTime = playTime;
356            mPlayingState = SEEKED;
357        }
358        mStartTime = currentTime - playTime;
359        animationFrame(currentTime);
360    }
361
362    /**
363     * Gets the current position of the animation in time, which is equal to the current
364     * time minus the time that the animation started. An animation that is not yet started will
365     * return a value of zero.
366     *
367     * @return The current position in time of the animation.
368     */
369    public long getCurrentPlayTime() {
370        if (!mInitialized || mPlayingState == STOPPED) {
371            return 0;
372        }
373        return AnimationUtils.currentAnimationTimeMillis() - mStartTime;
374    }
375
376    /**
377     * This custom, static handler handles the timing pulse that is shared by
378     * all active animations. This approach ensures that the setting of animation
379     * values will happen on the UI thread and that all animations will share
380     * the same times for calculating their values, which makes synchronizing
381     * animations possible.
382     *
383     */
384    private static class AnimationHandler extends Handler {
385        /**
386         * There are only two messages that we care about: ANIMATION_START and
387         * ANIMATION_FRAME. The START message is sent when an animation's start()
388         * method is called. It cannot start synchronously when start() is called
389         * because the call may be on the wrong thread, and it would also not be
390         * synchronized with other animations because it would not start on a common
391         * timing pulse. So each animation sends a START message to the handler, which
392         * causes the handler to place the animation on the active animations queue and
393         * start processing frames for that animation.
394         * The FRAME message is the one that is sent over and over while there are any
395         * active animations to process.
396         */
397        @Override
398        public void handleMessage(Message msg) {
399            boolean callAgain = true;
400            switch (msg.what) {
401                // TODO: should we avoid sending frame message when starting if we
402                // were already running?
403                case ANIMATION_START:
404                    if (sAnimations.size() > 0 || sDelayedAnims.size() > 0) {
405                        callAgain = false;
406                    }
407                    // pendingAnims holds any animations that have requested to be started
408                    // We're going to clear sPendingAnimations, but starting animation may
409                    // cause more to be added to the pending list (for example, if one animation
410                    // starting triggers another starting). So we loop until sPendingAnimations
411                    // is empty.
412                    while (sPendingAnimations.size() > 0) {
413                        ArrayList<ValueAnimator> pendingCopy =
414                                (ArrayList<ValueAnimator>) sPendingAnimations.clone();
415                        sPendingAnimations.clear();
416                        int count = pendingCopy.size();
417                        for (int i = 0; i < count; ++i) {
418                            ValueAnimator anim = pendingCopy.get(i);
419                            // If the animation has a startDelay, place it on the delayed list
420                            if (anim.mStartDelay == 0 || anim.mPlayingState == ENDED ||
421                                    anim.mPlayingState == CANCELED) {
422                                anim.startAnimation();
423                            } else {
424                                sDelayedAnims.add(anim);
425                            }
426                        }
427                    }
428                    // fall through to process first frame of new animations
429                case ANIMATION_FRAME:
430                    // currentTime holds the common time for all animations processed
431                    // during this frame
432                    long currentTime = AnimationUtils.currentAnimationTimeMillis();
433
434                    // First, process animations currently sitting on the delayed queue, adding
435                    // them to the active animations if they are ready
436                    int numDelayedAnims = sDelayedAnims.size();
437                    for (int i = 0; i < numDelayedAnims; ++i) {
438                        ValueAnimator anim = sDelayedAnims.get(i);
439                        if (anim.delayedAnimationFrame(currentTime)) {
440                            sReadyAnims.add(anim);
441                        }
442                    }
443                    int numReadyAnims = sReadyAnims.size();
444                    if (numReadyAnims > 0) {
445                        for (int i = 0; i < numReadyAnims; ++i) {
446                            ValueAnimator anim = sReadyAnims.get(i);
447                            anim.startAnimation();
448                            sDelayedAnims.remove(anim);
449                        }
450                        sReadyAnims.clear();
451                    }
452
453                    // Now process all active animations. The return value from animationFrame()
454                    // tells the handler whether it should now be ended
455                    int numAnims = sAnimations.size();
456                    for (int i = 0; i < numAnims; ++i) {
457                        ValueAnimator anim = sAnimations.get(i);
458                        if (anim.animationFrame(currentTime)) {
459                            sEndingAnims.add(anim);
460                        }
461                    }
462                    if (sEndingAnims.size() > 0) {
463                        for (int i = 0; i < sEndingAnims.size(); ++i) {
464                            sEndingAnims.get(i).endAnimation();
465                        }
466                        sEndingAnims.clear();
467                    }
468
469                    // If there are still active or delayed animations, call the handler again
470                    // after the frameDelay
471                    if (callAgain && (!sAnimations.isEmpty() || !sDelayedAnims.isEmpty())) {
472                        sendEmptyMessageDelayed(ANIMATION_FRAME,  Math.max(0, sFrameDelay -
473-                            (AnimationUtils.currentAnimationTimeMillis() - currentTime)));
474                    }
475                    break;
476            }
477        }
478    }
479
480    /**
481     * The amount of time, in milliseconds, to delay starting the animation after
482     * {@link #start()} is called.
483     *
484     * @return the number of milliseconds to delay running the animation
485     */
486    public long getStartDelay() {
487        return mStartDelay;
488    }
489
490    /**
491     * The amount of time, in milliseconds, to delay starting the animation after
492     * {@link #start()} is called.
493
494     * @param startDelay The amount of the delay, in milliseconds
495     */
496    public void setStartDelay(long startDelay) {
497        this.mStartDelay = startDelay;
498    }
499
500    /**
501     * The amount of time, in milliseconds, between each frame of the animation. This is a
502     * requested time that the animation will attempt to honor, but the actual delay between
503     * frames may be different, depending on system load and capabilities. This is a static
504     * function because the same delay will be applied to all animations, since they are all
505     * run off of a single timing loop.
506     *
507     * @return the requested time between frames, in milliseconds
508     */
509    public static long getFrameDelay() {
510        return sFrameDelay;
511    }
512
513    /**
514     * The amount of time, in milliseconds, between each frame of the animation. This is a
515     * requested time that the animation will attempt to honor, but the actual delay between
516     * frames may be different, depending on system load and capabilities. This is a static
517     * function because the same delay will be applied to all animations, since they are all
518     * run off of a single timing loop.
519     *
520     * @param frameDelay the requested time between frames, in milliseconds
521     */
522    public static void setFrameDelay(long frameDelay) {
523        sFrameDelay = frameDelay;
524    }
525
526    /**
527     * The most recent value calculated by this <code>ValueAnimator</code> when there is just one
528     * property being animated. This value is only sensible while the animation is running. The main
529     * purpose for this read-only property is to retrieve the value from the <code>ValueAnimator</code>
530     * during a call to {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
531     * is called during each animation frame, immediately after the value is calculated.
532     *
533     * @return animatedValue The value most recently calculated by this <code>ValueAnimator</code> for
534     * the single property being animated. If there are several properties being animated
535     * (specified by several PropertyValuesHolder objects in the constructor), this function
536     * returns the animated value for the first of those objects.
537     */
538    public Object getAnimatedValue() {
539        if (mValues != null && mValues.length > 0) {
540            return mValues[0].getAnimatedValue();
541        }
542        // Shouldn't get here; should always have values unless ValueAnimator was set up wrong
543        return null;
544    }
545
546    /**
547     * The most recent value calculated by this <code>ValueAnimator</code> for <code>propertyName</code>.
548     * The main purpose for this read-only property is to retrieve the value from the
549     * <code>ValueAnimator</code> during a call to
550     * {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
551     * is called during each animation frame, immediately after the value is calculated.
552     *
553     * @return animatedValue The value most recently calculated for the named property
554     * by this <code>ValueAnimator</code>.
555     */
556    public Object getAnimatedValue(String propertyName) {
557        PropertyValuesHolder valuesHolder = mValuesMap.get(propertyName);
558        if (valuesHolder != null) {
559            return valuesHolder.getAnimatedValue();
560        } else {
561            // At least avoid crashing if called with bogus propertyName
562            return null;
563        }
564    }
565
566    /**
567     * Sets how many times the animation should be repeated. If the repeat
568     * count is 0, the animation is never repeated. If the repeat count is
569     * greater than 0 or {@link #INFINITE}, the repeat mode will be taken
570     * into account. The repeat count is 0 by default.
571     *
572     * @param value the number of times the animation should be repeated
573     */
574    public void setRepeatCount(int value) {
575        mRepeatCount = value;
576    }
577    /**
578     * Defines how many times the animation should repeat. The default value
579     * is 0.
580     *
581     * @return the number of times the animation should repeat, or {@link #INFINITE}
582     */
583    public int getRepeatCount() {
584        return mRepeatCount;
585    }
586
587    /**
588     * Defines what this animation should do when it reaches the end. This
589     * setting is applied only when the repeat count is either greater than
590     * 0 or {@link #INFINITE}. Defaults to {@link #RESTART}.
591     *
592     * @param value {@link #RESTART} or {@link #REVERSE}
593     */
594    public void setRepeatMode(int value) {
595        mRepeatMode = value;
596    }
597
598    /**
599     * Defines what this animation should do when it reaches the end.
600     *
601     * @return either one of {@link #REVERSE} or {@link #RESTART}
602     */
603    public int getRepeatMode() {
604        return mRepeatMode;
605    }
606
607    /**
608     * Adds a listener to the set of listeners that are sent update events through the life of
609     * an animation. This method is called on all listeners for every frame of the animation,
610     * after the values for the animation have been calculated.
611     *
612     * @param listener the listener to be added to the current set of listeners for this animation.
613     */
614    public void addUpdateListener(AnimatorUpdateListener listener) {
615        if (mUpdateListeners == null) {
616            mUpdateListeners = new ArrayList<AnimatorUpdateListener>();
617        }
618        mUpdateListeners.add(listener);
619    }
620
621    /**
622     * Removes all listeners from the set listening to frame updates for this animation.
623     */
624    public void removeAllUpdateListeners() {
625        if (mUpdateListeners == null) {
626            return;
627        }
628        mUpdateListeners.clear();
629        mUpdateListeners = null;
630    }
631
632    /**
633     * Removes a listener from the set listening to frame updates for this animation.
634     *
635     * @param listener the listener to be removed from the current set of update listeners
636     * for this animation.
637     */
638    public void removeUpdateListener(AnimatorUpdateListener listener) {
639        if (mUpdateListeners == null) {
640            return;
641        }
642        mUpdateListeners.remove(listener);
643        if (mUpdateListeners.size() == 0) {
644            mUpdateListeners = null;
645        }
646    }
647
648
649    /**
650     * The time interpolator used in calculating the elapsed fraction of this animation. The
651     * interpolator determines whether the animation runs with linear or non-linear motion,
652     * such as acceleration and deceleration. The default value is
653     * {@link android.view.animation.AccelerateDecelerateInterpolator}
654     *
655     * @param value the interpolator to be used by this animation
656     */
657    @Override
658    public void setInterpolator(TimeInterpolator value) {
659        if (value != null) {
660            mInterpolator = value;
661        }
662    }
663
664    /**
665     * Returns the timing interpolator that this ValueAnimator uses.
666     *
667     * @return The timing interpolator for this ValueAnimator.
668     */
669    public TimeInterpolator getInterpolator() {
670        return mInterpolator;
671    }
672
673    /**
674     * The type evaluator to be used when calculating the animated values of this animation.
675     * The system will automatically assign a float, int, or double evaluator based on the type
676     * of <code>startValue</code> and <code>endValue</code> in the constructor. But if these values
677     * are not one of these primitive types, or if different evaluation is desired (such as is
678     * necessary with int values that represent colors), a custom evaluator needs to be assigned.
679     * For example, when running an animation on color values, the {@link RGBEvaluator}
680     * should be used to get correct RGB color interpolation.
681     *
682     * <p>If this ValueAnimator has only one set of values being animated between, this evaluator
683     * will be used for that set. If there are several sets of values being animated, which is
684     * the case if PropertyValuesHOlder objects were set on the ValueAnimator, then the evaluator
685     * is assigned just to the first PropertyValuesHolder object.</p>
686     *
687     * @param value the evaluator to be used this animation
688     */
689    public void setEvaluator(TypeEvaluator value) {
690        if (value != null && mValues != null && mValues.length > 0) {
691            mValues[0].setEvaluator(value);
692        }
693    }
694
695    /**
696     * Start the animation playing. This version of start() takes a boolean flag that indicates
697     * whether the animation should play in reverse. The flag is usually false, but may be set
698     * to true if called from the reverse() method/
699     *
700     * @param playBackwards Whether the ValueAnimator should start playing in reverse.
701     */
702    private void start(boolean playBackwards) {
703        mPlayingBackwards = playBackwards;
704        Looper looper = Looper.getMainLooper();
705        final boolean isUiThread;
706        if (looper != null) {
707            isUiThread = Thread.currentThread() == looper.getThread();
708        } else {
709            // ignore check if we don't have a Looper (this isn't an Activity)
710            isUiThread = true;
711        }
712        if ((mStartDelay == 0) && isUiThread) {
713            if (mListeners != null) {
714                ArrayList<AnimatorListener> tmpListeners =
715                        (ArrayList<AnimatorListener>) mListeners.clone();
716                for (AnimatorListener listener : tmpListeners) {
717                    listener.onAnimationStart(this);
718                }
719            }
720            // This sets the initial value of the animation, prior to actually starting it running
721            setCurrentPlayTime(getCurrentPlayTime());
722        }
723        mPlayingState = STOPPED;
724        mStartedDelay = false;
725        sPendingAnimations.add(this);
726        if (sAnimationHandler == null) {
727            sAnimationHandler = new AnimationHandler();
728        }
729        // TODO: does this put too many messages on the queue if the handler
730        // is already running?
731        sAnimationHandler.sendEmptyMessage(ANIMATION_START);
732    }
733
734    @Override
735    public void start() {
736        start(false);
737    }
738
739    @Override
740    public void cancel() {
741        if (mListeners != null) {
742            ArrayList<AnimatorListener> tmpListeners =
743                    (ArrayList<AnimatorListener>) mListeners.clone();
744            for (AnimatorListener listener : tmpListeners) {
745                listener.onAnimationCancel(this);
746            }
747        }
748        // Just set the CANCELED flag - this causes the animation to end the next time a frame
749        // is processed.
750        mPlayingState = CANCELED;
751    }
752
753    @Override
754    public void end() {
755        if (!sAnimations.contains(this) && !sPendingAnimations.contains(this)) {
756            // Special case if the animation has not yet started; get it ready for ending
757            mStartedDelay = false;
758            sPendingAnimations.add(this);
759            if (sAnimationHandler == null) {
760                sAnimationHandler = new AnimationHandler();
761            }
762            sAnimationHandler.sendEmptyMessage(ANIMATION_START);
763        }
764        // Just set the ENDED flag - this causes the animation to end the next time a frame
765        // is processed.
766        mPlayingState = ENDED;
767    }
768
769    @Override
770    public boolean isRunning() {
771        // ENDED or CANCELED indicate that it has been ended or canceled, but not processed yet
772        return (mPlayingState == RUNNING || mPlayingState == ENDED || mPlayingState == CANCELED);
773    }
774
775    /**
776     * Plays the ValueAnimator in reverse. If the animation is already running,
777     * it will stop itself and play backwards from the point reached when reverse was called.
778     * If the animation is not currently running, then it will start from the end and
779     * play backwards. This behavior is only set for the current animation; future playing
780     * of the animation will use the default behavior of playing forward.
781     */
782    public void reverse() {
783        mPlayingBackwards = !mPlayingBackwards;
784        if (mPlayingState == RUNNING) {
785            long currentTime = AnimationUtils.currentAnimationTimeMillis();
786            long currentPlayTime = currentTime - mStartTime;
787            long timeLeft = mDuration - currentPlayTime;
788            mStartTime = currentTime - timeLeft;
789        } else {
790            start(true);
791        }
792    }
793
794    /**
795     * Called internally to end an animation by removing it from the animations list. Must be
796     * called on the UI thread.
797     */
798    private void endAnimation() {
799        sAnimations.remove(this);
800        mPlayingState = STOPPED;
801        if (mListeners != null) {
802            ArrayList<AnimatorListener> tmpListeners =
803                    (ArrayList<AnimatorListener>) mListeners.clone();
804            for (AnimatorListener listener : tmpListeners) {
805                listener.onAnimationEnd(this);
806            }
807        }
808    }
809
810    /**
811     * Called internally to start an animation by adding it to the active animations list. Must be
812     * called on the UI thread.
813     */
814    private void startAnimation() {
815        initAnimation();
816        sAnimations.add(this);
817        if (mStartDelay > 0 && mListeners != null) {
818            // Listeners were already notified in start() if startDelay is 0; this is
819            // just for delayed animations
820            ArrayList<AnimatorListener> tmpListeners =
821                    (ArrayList<AnimatorListener>) mListeners.clone();
822            for (AnimatorListener listener : tmpListeners) {
823                listener.onAnimationStart(this);
824            }
825        }
826    }
827
828    /**
829     * Internal function called to process an animation frame on an animation that is currently
830     * sleeping through its <code>startDelay</code> phase. The return value indicates whether it
831     * should be woken up and put on the active animations queue.
832     *
833     * @param currentTime The current animation time, used to calculate whether the animation
834     * has exceeded its <code>startDelay</code> and should be started.
835     * @return True if the animation's <code>startDelay</code> has been exceeded and the animation
836     * should be added to the set of active animations.
837     */
838    private boolean delayedAnimationFrame(long currentTime) {
839        if (mPlayingState == CANCELED || mPlayingState == ENDED) {
840            // end the delay, process an animation frame to actually cancel it
841            return true;
842        }
843        if (!mStartedDelay) {
844            mStartedDelay = true;
845            mDelayStartTime = currentTime;
846        } else {
847            long deltaTime = currentTime - mDelayStartTime;
848            if (deltaTime > mStartDelay) {
849                // startDelay ended - start the anim and record the
850                // mStartTime appropriately
851                mStartTime = currentTime - (deltaTime - mStartDelay);
852                mPlayingState = RUNNING;
853                return true;
854            }
855        }
856        return false;
857    }
858
859    /**
860     * This internal function processes a single animation frame for a given animation. The
861     * currentTime parameter is the timing pulse sent by the handler, used to calculate the
862     * elapsed duration, and therefore
863     * the elapsed fraction, of the animation. The return value indicates whether the animation
864     * should be ended (which happens when the elapsed time of the animation exceeds the
865     * animation's duration, including the repeatCount).
866     *
867     * @param currentTime The current time, as tracked by the static timing handler
868     * @return true if the animation's duration, including any repetitions due to
869     * <code>repeatCount</code> has been exceeded and the animation should be ended.
870     */
871    private boolean animationFrame(long currentTime) {
872        boolean done = false;
873
874        if (mPlayingState == STOPPED) {
875            mPlayingState = RUNNING;
876            if (mSeekTime < 0) {
877                mStartTime = currentTime;
878            } else {
879                mStartTime = currentTime - mSeekTime;
880                // Now that we're playing, reset the seek time
881                mSeekTime = -1;
882            }
883        }
884        switch (mPlayingState) {
885        case RUNNING:
886        case SEEKED:
887            float fraction = (float)(currentTime - mStartTime) / mDuration;
888            if (fraction >= 1f) {
889                if (mCurrentIteration < mRepeatCount || mRepeatCount == INFINITE) {
890                    // Time to repeat
891                    if (mListeners != null) {
892                        for (AnimatorListener listener : mListeners) {
893                            listener.onAnimationRepeat(this);
894                        }
895                    }
896                    ++mCurrentIteration;
897                    if (mRepeatMode == REVERSE) {
898                        mPlayingBackwards = mPlayingBackwards ? false : true;
899                    }
900                    // TODO: doesn't account for fraction going Wayyyyy over 1, like 2+
901                    fraction = fraction - 1f;
902                    mStartTime += mDuration;
903                } else {
904                    done = true;
905                    fraction = Math.min(fraction, 1.0f);
906                }
907            }
908            if (mPlayingBackwards) {
909                fraction = 1f - fraction;
910            }
911            animateValue(fraction);
912            break;
913        case ENDED:
914            // The final value set on the target varies, depending on whether the animation
915            // was supposed to repeat an odd number of times
916            if (mRepeatCount > 0 && (mRepeatCount & 0x01) == 1) {
917                animateValue(0f);
918            } else {
919                animateValue(1f);
920            }
921            // Fall through to set done flag
922        case CANCELED:
923            done = true;
924            mPlayingState = STOPPED;
925            break;
926        }
927
928        return done;
929    }
930
931    /**
932     * This method is called with the elapsed fraction of the animation during every
933     * animation frame. This function turns the elapsed fraction into an interpolated fraction
934     * and then into an animated value (from the evaluator. The function is called mostly during
935     * animation updates, but it is also called when the <code>end()</code>
936     * function is called, to set the final value on the property.
937     *
938     * <p>Overrides of this method must call the superclass to perform the calculation
939     * of the animated value.</p>
940     *
941     * @param fraction The elapsed fraction of the animation.
942     */
943    void animateValue(float fraction) {
944        fraction = mInterpolator.getInterpolation(fraction);
945        int numValues = mValues.length;
946        for (int i = 0; i < numValues; ++i) {
947            mValues[i].calculateValue(fraction);
948        }
949        if (mUpdateListeners != null) {
950            int numListeners = mUpdateListeners.size();
951            for (int i = 0; i < numListeners; ++i) {
952                mUpdateListeners.get(i).onAnimationUpdate(this);
953            }
954        }
955    }
956
957    @Override
958    public ValueAnimator clone() {
959        final ValueAnimator anim = (ValueAnimator) super.clone();
960        if (mUpdateListeners != null) {
961            ArrayList<AnimatorUpdateListener> oldListeners = mUpdateListeners;
962            anim.mUpdateListeners = new ArrayList<AnimatorUpdateListener>();
963            int numListeners = oldListeners.size();
964            for (int i = 0; i < numListeners; ++i) {
965                anim.mUpdateListeners.add(oldListeners.get(i));
966            }
967        }
968        anim.mSeekTime = -1;
969        anim.mPlayingBackwards = false;
970        anim.mCurrentIteration = 0;
971        anim.mInitialized = false;
972        anim.mPlayingState = STOPPED;
973        anim.mStartedDelay = false;
974        PropertyValuesHolder[] oldValues = mValues;
975        if (oldValues != null) {
976            int numValues = oldValues.length;
977            anim.mValues = new PropertyValuesHolder[numValues];
978            for (int i = 0; i < numValues; ++i) {
979                anim.mValues[i] = oldValues[i].clone();
980            }
981            anim.mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues);
982            for (int i = 0; i < numValues; ++i) {
983                PropertyValuesHolder valuesHolder = mValues[i];
984                anim.mValuesMap.put(valuesHolder.getPropertyName(), valuesHolder);
985            }
986        }
987        return anim;
988    }
989
990    /**
991     * Implementors of this interface can add themselves as update listeners
992     * to an <code>ValueAnimator</code> instance to receive callbacks on every animation
993     * frame, after the current frame's values have been calculated for that
994     * <code>ValueAnimator</code>.
995     */
996    public static interface AnimatorUpdateListener {
997        /**
998         * <p>Notifies the occurrence of another frame of the animation.</p>
999         *
1000         * @param animation The animation which was repeated.
1001         */
1002        void onAnimationUpdate(ValueAnimator animation);
1003
1004    }
1005}