ValueAnimator.java revision 2794eb3b02e2404d453d3ad22a8a85a138130a07
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 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 = 300;
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 factory methods which take parameters are more generally
222     * useful.
223     */
224    public ValueAnimator() {
225    }
226
227    /**
228     * Constructs and returns a ValueAnimator that animates between int values. A single
229     * value implies that that value is the one being animated to. However, this is not typically
230     * useful in a ValueAnimator object because there is no way for the object to determine the
231     * starting value for the animation (unlike ObjectAnimator, which can derive that value
232     * from the target object and property being animated). Therefore, there should typically
233     * be two or more values.
234     *
235     * @param values A set of values that the animation will animate between over time.
236     * @return A ValueAnimator object that is set up to animate between the given values.
237     */
238    public static ValueAnimator ofInt(int... values) {
239        ValueAnimator anim = new ValueAnimator();
240        anim.setIntValues(values);
241        return anim;
242    }
243
244    /**
245     * Constructs and returns a ValueAnimator that animates between float values. A single
246     * value implies that that value is the one being animated to. However, this is not typically
247     * useful in a ValueAnimator object because there is no way for the object to determine the
248     * starting value for the animation (unlike ObjectAnimator, which can derive that value
249     * from the target object and property being animated). Therefore, there should typically
250     * be two or more values.
251     *
252     * @param values A set of values that the animation will animate between over time.
253     * @return A ValueAnimator object that is set up to animate between the given values.
254     */
255    public static ValueAnimator ofFloat(float... values) {
256        ValueAnimator anim = new ValueAnimator();
257        anim.setFloatValues(values);
258        return anim;
259    }
260
261    /**
262     * Constructs and returns a ValueAnimator that animates between double values. A single
263     * value implies that that value is the one being animated to. However, this is not typically
264     * useful in a ValueAnimator object because there is no way for the object to determine the
265     * starting value for the animation (unlike ObjectAnimator, which can derive that value
266     * from the target object and property being animated). Therefore, there should typically
267     * be two or more values.
268     *
269     * @param values A set of values that the animation will animate between over time.
270     * @return A ValueAnimator object that is set up to animate between the given values.
271     */
272    public static ValueAnimator ofDouble(double... values) {
273        ValueAnimator anim = new ValueAnimator();
274        anim.setDoubleValues(values);
275        return anim;
276    }
277
278    /**
279     * Constructs and returns a ValueAnimator that animates between long values. A single
280     * value implies that that value is the one being animated to. However, this is not typically
281     * useful in a ValueAnimator object because there is no way for the object to determine the
282     * starting value for the animation (unlike ObjectAnimator, which can derive that value
283     * from the target object and property being animated). Therefore, there should typically
284     * be two or more values.
285     *
286     * @param values A set of values that the animation will animate between over time.
287     * @return A ValueAnimator object that is set up to animate between the given values.
288     */
289    public static ValueAnimator ofLong(long... values) {
290        ValueAnimator anim = new ValueAnimator();
291        anim.setLongValues(values);
292        return anim;
293    }
294
295    /**
296     * Constructs and returns a ValueAnimator that animates between the values
297     * specified in the PropertyValuesHolder objects.
298     *
299     * @param values A set of PropertyValuesHolder objects whose values will be animated
300     * between over time.
301     * @return A ValueAnimator object that is set up to animate between the given values.
302     */
303    public static ValueAnimator ofPropertyValuesHolder(PropertyValuesHolder... values) {
304        ValueAnimator anim = new ValueAnimator();
305        anim.setValues(values);
306        return anim;
307    }
308    /**
309     * Constructs and returns a ValueAnimator that animates between Object values. A single
310     * value implies that that value is the one being animated to. However, this is not typically
311     * useful in a ValueAnimator object because there is no way for the object to determine the
312     * starting value for the animation (unlike ObjectAnimator, which can derive that value
313     * from the target object and property being animated). Therefore, there should typically
314     * be two or more values.
315     *
316     * <p>Since ValueAnimator does not know how to animate between arbitrary Objects, this
317     * factory method also takes a TypeEvaluator object that the ValueAnimator will use
318     * to perform that interpolation.
319     *
320     * @param evaluator A TypeEvaluator that will be called on each animation frame to
321     * provide the ncessry interpolation between the Object values to derive the animated
322     * value.
323     * @param values A set of values that the animation will animate between over time.
324     * @return A ValueAnimator object that is set up to animate between the given values.
325     */
326    public static ValueAnimator ofObject(TypeEvaluator evaluator, Object... values) {
327        ValueAnimator anim = new ValueAnimator();
328        anim.setObjectValues(values);
329        anim.setEvaluator(evaluator);
330        return anim;
331    }
332
333    /**
334     * Sets int values that will be animated between. A single
335     * value implies that that value is the one being animated to. However, this is not typically
336     * useful in a ValueAnimator object because there is no way for the object to determine the
337     * starting value for the animation (unlike ObjectAnimator, which can derive that value
338     * from the target object and property being animated). Therefore, there should typically
339     * be two or more values.
340     *
341     * <p>If there are already multiple sets of values defined for this ValueAnimator via more
342     * than one PropertyValuesHolder object, this method will set the values for the first
343     * of those objects.</p>
344     *
345     * @param values A set of values that the animation will animate between over time.
346     */
347    public void setIntValues(int... values) {
348        if (values == null || values.length == 0) {
349            return;
350        }
351        if (mValues == null || mValues.length == 0) {
352            setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofInt("", values)});
353        } else {
354            PropertyValuesHolder valuesHolder = mValues[0];
355            valuesHolder.setIntValues(values);
356        }
357        // New property/values/target should cause re-initialization prior to starting
358        mInitialized = false;
359    }
360
361    /**
362     * Sets float values that will be animated between. A single
363     * value implies that that value is the one being animated to. However, this is not typically
364     * useful in a ValueAnimator object because there is no way for the object to determine the
365     * starting value for the animation (unlike ObjectAnimator, which can derive that value
366     * from the target object and property being animated). Therefore, there should typically
367     * be two or more values.
368     *
369     * <p>If there are already multiple sets of values defined for this ValueAnimator via more
370     * than one PropertyValuesHolder object, this method will set the values for the first
371     * of those objects.</p>
372     *
373     * @param values A set of values that the animation will animate between over time.
374     */
375    public void setFloatValues(float... values) {
376        if (values == null || values.length == 0) {
377            return;
378        }
379        if (mValues == null || mValues.length == 0) {
380            setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofFloat("", values)});
381        } else {
382            PropertyValuesHolder valuesHolder = mValues[0];
383            valuesHolder.setFloatValues(values);
384        }
385        // New property/values/target should cause re-initialization prior to starting
386        mInitialized = false;
387    }
388
389    /**
390     * Sets long values that will be animated between. A single
391     * value implies that that value is the one being animated to. However, this is not typically
392     * useful in a ValueAnimator object because there is no way for the object to determine the
393     * starting value for the animation (unlike ObjectAnimator, which can derive that value
394     * from the target object and property being animated). Therefore, there should typically
395     * be two or more values.
396     *
397     * <p>If there are already multiple sets of values defined for this ValueAnimator via more
398     * than one PropertyValuesHolder object, this method will set the values for the first
399     * of those objects.</p>
400     *
401     * @param values A set of values that the animation will animate between over time.
402     */
403    public void setLongValues(long... values) {
404        if (values == null || values.length == 0) {
405            return;
406        }
407        if (mValues == null || mValues.length == 0) {
408            setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofLong("", values)});
409        } else {
410            PropertyValuesHolder valuesHolder = mValues[0];
411            valuesHolder.setLongValues(values);
412        }
413        // New property/values/target should cause re-initialization prior to starting
414        mInitialized = false;
415    }
416
417    /**
418     * Sets double values that will be animated between. A single
419     * value implies that that value is the one being animated to. However, this is not typically
420     * useful in a ValueAnimator object because there is no way for the object to determine the
421     * starting value for the animation (unlike ObjectAnimator, which can derive that value
422     * from the target object and property being animated). Therefore, there should typically
423     * be two or more values.
424     *
425     * <p>If there are already multiple sets of values defined for this ValueAnimator via more
426     * than one PropertyValuesHolder object, this method will set the values for the first
427     * of those objects.</p>
428     *
429     * @param values A set of values that the animation will animate between over time.
430     */
431    public void setDoubleValues(double... values) {
432        if (values == null || values.length == 0) {
433            return;
434        }
435        if (mValues == null || mValues.length == 0) {
436            setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofDouble("", values)});
437        } else {
438            PropertyValuesHolder valuesHolder = mValues[0];
439            valuesHolder.setDoubleValues(values);
440        }
441        // New property/values/target should cause re-initialization prior to starting
442        mInitialized = false;
443    }
444
445    /**
446     * Sets the values to animate between for this animation. A single
447     * value implies that that value is the one being animated to. However, this is not typically
448     * useful in a ValueAnimator object because there is no way for the object to determine the
449     * starting value for the animation (unlike ObjectAnimator, which can derive that value
450     * from the target object and property being animated). Therefore, there should typically
451     * be two or more values.
452     *
453     * <p>If there are already multiple sets of values defined for this ValueAnimator via more
454     * than one PropertyValuesHolder object, this method will set the values for the first
455     * of those objects.</p>
456     *
457     * <p>There should be a TypeEvaluator set on the ValueAnimator that knows how to interpolate
458     * between these value objects. ValueAnimator only knows how to interpolate between the
459     * primitive types specified in the other setValues() methods.</p>
460     *
461     * @param values The set of values to animate between.
462     */
463    public void setObjectValues(Object... values) {
464        if (values == null || values.length == 0) {
465            return;
466        }
467        if (mValues == null || mValues.length == 0) {
468            setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofObject("",
469                    (TypeEvaluator)null, values)});
470        } else {
471            PropertyValuesHolder valuesHolder = mValues[0];
472            valuesHolder.setObjectValues(values);
473        }
474        // New property/values/target should cause re-initialization prior to starting
475        mInitialized = false;
476    }
477
478    /**
479     * Sets the values, per property, being animated between. This function is called internally
480     * by the constructors of ValueAnimator that take a list of values. But an ValueAnimator can
481     * be constructed without values and this method can be called to set the values manually
482     * instead.
483     *
484     * @param values The set of values, per property, being animated between.
485     */
486    public void setValues(PropertyValuesHolder... values) {
487        int numValues = values.length;
488        mValues = values;
489        mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues);
490        for (int i = 0; i < numValues; ++i) {
491            PropertyValuesHolder valuesHolder = (PropertyValuesHolder) values[i];
492            mValuesMap.put(valuesHolder.getPropertyName(), valuesHolder);
493        }
494        // New property/values/target should cause re-initialization prior to starting
495        mInitialized = false;
496    }
497
498    /**
499     * Returns the values that this ValueAnimator animates between. These values are stored in
500     * PropertyValuesHolder objects, even if the ValueAnimator was created with a simple list
501     * of value objects instead.
502     *
503     * @return PropertyValuesHolder[] An array of PropertyValuesHolder objects which hold the
504     * values, per property, that define the animation.
505     */
506    public PropertyValuesHolder[] getValues() {
507        return mValues;
508    }
509
510    /**
511     * This function is called immediately before processing the first animation
512     * frame of an animation. If there is a nonzero <code>startDelay</code>, the
513     * function is called after that delay ends.
514     * It takes care of the final initialization steps for the
515     * animation.
516     *
517     *  <p>Overrides of this method should call the superclass method to ensure
518     *  that internal mechanisms for the animation are set up correctly.</p>
519     */
520    void initAnimation() {
521        if (!mInitialized) {
522            int numValues = mValues.length;
523            for (int i = 0; i < numValues; ++i) {
524                mValues[i].init();
525            }
526            mCurrentIteration = 0;
527            mInitialized = true;
528        }
529    }
530
531
532    /**
533     * Sets the length of the animation. The default duration is 300 milliseconds.
534     *
535     * @param duration The length of the animation, in milliseconds.
536     * @return ValueAnimator The object called with setDuration(). This return
537     * value makes it easier to compose statements together that construct and then set the
538     * duration, as in <code>ValueAnimator.ofInt(0, 10).setDuration(500).start()</code>.
539     */
540    public ValueAnimator setDuration(long duration) {
541        mDuration = duration;
542        return this;
543    }
544
545    /**
546     * Gets the length of the animation. The default duration is 300 milliseconds.
547     *
548     * @return The length of the animation, in milliseconds.
549     */
550    public long getDuration() {
551        return mDuration;
552    }
553
554    /**
555     * Sets the position of the animation to the specified point in time. This time should
556     * be between 0 and the total duration of the animation, including any repetition. If
557     * the animation has not yet been started, then it will not advance forward after it is
558     * set to this time; it will simply set the time to this value and perform any appropriate
559     * actions based on that time. If the animation is already running, then setCurrentPlayTime()
560     * will set the current playing time to this value and continue playing from that point.
561     *
562     * @param playTime The time, in milliseconds, to which the animation is advanced or rewound.
563     */
564    public void setCurrentPlayTime(long playTime) {
565        initAnimation();
566        long currentTime = AnimationUtils.currentAnimationTimeMillis();
567        if (mPlayingState != RUNNING) {
568            mSeekTime = playTime;
569            mPlayingState = SEEKED;
570        }
571        mStartTime = currentTime - playTime;
572        animationFrame(currentTime);
573    }
574
575    /**
576     * Gets the current position of the animation in time, which is equal to the current
577     * time minus the time that the animation started. An animation that is not yet started will
578     * return a value of zero.
579     *
580     * @return The current position in time of the animation.
581     */
582    public long getCurrentPlayTime() {
583        if (!mInitialized || mPlayingState == STOPPED) {
584            return 0;
585        }
586        return AnimationUtils.currentAnimationTimeMillis() - mStartTime;
587    }
588
589    /**
590     * This custom, static handler handles the timing pulse that is shared by
591     * all active animations. This approach ensures that the setting of animation
592     * values will happen on the UI thread and that all animations will share
593     * the same times for calculating their values, which makes synchronizing
594     * animations possible.
595     *
596     */
597    private static class AnimationHandler extends Handler {
598        /**
599         * There are only two messages that we care about: ANIMATION_START and
600         * ANIMATION_FRAME. The START message is sent when an animation's start()
601         * method is called. It cannot start synchronously when start() is called
602         * because the call may be on the wrong thread, and it would also not be
603         * synchronized with other animations because it would not start on a common
604         * timing pulse. So each animation sends a START message to the handler, which
605         * causes the handler to place the animation on the active animations queue and
606         * start processing frames for that animation.
607         * The FRAME message is the one that is sent over and over while there are any
608         * active animations to process.
609         */
610        @Override
611        public void handleMessage(Message msg) {
612            boolean callAgain = true;
613            switch (msg.what) {
614                // TODO: should we avoid sending frame message when starting if we
615                // were already running?
616                case ANIMATION_START:
617                    if (sAnimations.size() > 0 || sDelayedAnims.size() > 0) {
618                        callAgain = false;
619                    }
620                    // pendingAnims holds any animations that have requested to be started
621                    // We're going to clear sPendingAnimations, but starting animation may
622                    // cause more to be added to the pending list (for example, if one animation
623                    // starting triggers another starting). So we loop until sPendingAnimations
624                    // is empty.
625                    while (sPendingAnimations.size() > 0) {
626                        ArrayList<ValueAnimator> pendingCopy =
627                                (ArrayList<ValueAnimator>) sPendingAnimations.clone();
628                        sPendingAnimations.clear();
629                        int count = pendingCopy.size();
630                        for (int i = 0; i < count; ++i) {
631                            ValueAnimator anim = pendingCopy.get(i);
632                            // If the animation has a startDelay, place it on the delayed list
633                            if (anim.mStartDelay == 0 || anim.mPlayingState == ENDED ||
634                                    anim.mPlayingState == CANCELED) {
635                                anim.startAnimation();
636                            } else {
637                                sDelayedAnims.add(anim);
638                            }
639                        }
640                    }
641                    // fall through to process first frame of new animations
642                case ANIMATION_FRAME:
643                    // currentTime holds the common time for all animations processed
644                    // during this frame
645                    long currentTime = AnimationUtils.currentAnimationTimeMillis();
646
647                    // First, process animations currently sitting on the delayed queue, adding
648                    // them to the active animations if they are ready
649                    int numDelayedAnims = sDelayedAnims.size();
650                    for (int i = 0; i < numDelayedAnims; ++i) {
651                        ValueAnimator anim = sDelayedAnims.get(i);
652                        if (anim.delayedAnimationFrame(currentTime)) {
653                            sReadyAnims.add(anim);
654                        }
655                    }
656                    int numReadyAnims = sReadyAnims.size();
657                    if (numReadyAnims > 0) {
658                        for (int i = 0; i < numReadyAnims; ++i) {
659                            ValueAnimator anim = sReadyAnims.get(i);
660                            anim.startAnimation();
661                            sDelayedAnims.remove(anim);
662                        }
663                        sReadyAnims.clear();
664                    }
665
666                    // Now process all active animations. The return value from animationFrame()
667                    // tells the handler whether it should now be ended
668                    int numAnims = sAnimations.size();
669                    for (int i = 0; i < numAnims; ++i) {
670                        ValueAnimator anim = sAnimations.get(i);
671                        if (anim.animationFrame(currentTime)) {
672                            sEndingAnims.add(anim);
673                        }
674                    }
675                    if (sEndingAnims.size() > 0) {
676                        for (int i = 0; i < sEndingAnims.size(); ++i) {
677                            sEndingAnims.get(i).endAnimation();
678                        }
679                        sEndingAnims.clear();
680                    }
681
682                    // If there are still active or delayed animations, call the handler again
683                    // after the frameDelay
684                    if (callAgain && (!sAnimations.isEmpty() || !sDelayedAnims.isEmpty())) {
685                        sendEmptyMessageDelayed(ANIMATION_FRAME,  Math.max(0, sFrameDelay -
686-                            (AnimationUtils.currentAnimationTimeMillis() - currentTime)));
687                    }
688                    break;
689            }
690        }
691    }
692
693    /**
694     * The amount of time, in milliseconds, to delay starting the animation after
695     * {@link #start()} is called.
696     *
697     * @return the number of milliseconds to delay running the animation
698     */
699    public long getStartDelay() {
700        return mStartDelay;
701    }
702
703    /**
704     * The amount of time, in milliseconds, to delay starting the animation after
705     * {@link #start()} is called.
706
707     * @param startDelay The amount of the delay, in milliseconds
708     */
709    public void setStartDelay(long startDelay) {
710        this.mStartDelay = startDelay;
711    }
712
713    /**
714     * The amount of time, in milliseconds, between each frame of the animation. This is a
715     * requested time that the animation will attempt to honor, but the actual delay between
716     * frames may be different, depending on system load and capabilities. This is a static
717     * function because the same delay will be applied to all animations, since they are all
718     * run off of a single timing loop.
719     *
720     * @return the requested time between frames, in milliseconds
721     */
722    public static long getFrameDelay() {
723        return sFrameDelay;
724    }
725
726    /**
727     * The amount of time, in milliseconds, between each frame of the animation. This is a
728     * requested time that the animation will attempt to honor, but the actual delay between
729     * frames may be different, depending on system load and capabilities. This is a static
730     * function because the same delay will be applied to all animations, since they are all
731     * run off of a single timing loop.
732     *
733     * @param frameDelay the requested time between frames, in milliseconds
734     */
735    public static void setFrameDelay(long frameDelay) {
736        sFrameDelay = frameDelay;
737    }
738
739    /**
740     * The most recent value calculated by this <code>ValueAnimator</code> when there is just one
741     * property being animated. This value is only sensible while the animation is running. The main
742     * purpose for this read-only property is to retrieve the value from the <code>ValueAnimator</code>
743     * during a call to {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
744     * is called during each animation frame, immediately after the value is calculated.
745     *
746     * @return animatedValue The value most recently calculated by this <code>ValueAnimator</code> for
747     * the single property being animated. If there are several properties being animated
748     * (specified by several PropertyValuesHolder objects in the constructor), this function
749     * returns the animated value for the first of those objects.
750     */
751    public Object getAnimatedValue() {
752        if (mValues != null && mValues.length > 0) {
753            return mValues[0].getAnimatedValue();
754        }
755        // Shouldn't get here; should always have values unless ValueAnimator was set up wrong
756        return null;
757    }
758
759    /**
760     * The most recent value calculated by this <code>ValueAnimator</code> for <code>propertyName</code>.
761     * The main purpose for this read-only property is to retrieve the value from the
762     * <code>ValueAnimator</code> during a call to
763     * {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
764     * is called during each animation frame, immediately after the value is calculated.
765     *
766     * @return animatedValue The value most recently calculated for the named property
767     * by this <code>ValueAnimator</code>.
768     */
769    public Object getAnimatedValue(String propertyName) {
770        PropertyValuesHolder valuesHolder = mValuesMap.get(propertyName);
771        if (valuesHolder != null) {
772            return valuesHolder.getAnimatedValue();
773        } else {
774            // At least avoid crashing if called with bogus propertyName
775            return null;
776        }
777    }
778
779    /**
780     * Sets how many times the animation should be repeated. If the repeat
781     * count is 0, the animation is never repeated. If the repeat count is
782     * greater than 0 or {@link #INFINITE}, the repeat mode will be taken
783     * into account. The repeat count is 0 by default.
784     *
785     * @param value the number of times the animation should be repeated
786     */
787    public void setRepeatCount(int value) {
788        mRepeatCount = value;
789    }
790    /**
791     * Defines how many times the animation should repeat. The default value
792     * is 0.
793     *
794     * @return the number of times the animation should repeat, or {@link #INFINITE}
795     */
796    public int getRepeatCount() {
797        return mRepeatCount;
798    }
799
800    /**
801     * Defines what this animation should do when it reaches the end. This
802     * setting is applied only when the repeat count is either greater than
803     * 0 or {@link #INFINITE}. Defaults to {@link #RESTART}.
804     *
805     * @param value {@link #RESTART} or {@link #REVERSE}
806     */
807    public void setRepeatMode(int value) {
808        mRepeatMode = value;
809    }
810
811    /**
812     * Defines what this animation should do when it reaches the end.
813     *
814     * @return either one of {@link #REVERSE} or {@link #RESTART}
815     */
816    public int getRepeatMode() {
817        return mRepeatMode;
818    }
819
820    /**
821     * Adds a listener to the set of listeners that are sent update events through the life of
822     * an animation. This method is called on all listeners for every frame of the animation,
823     * after the values for the animation have been calculated.
824     *
825     * @param listener the listener to be added to the current set of listeners for this animation.
826     */
827    public void addUpdateListener(AnimatorUpdateListener listener) {
828        if (mUpdateListeners == null) {
829            mUpdateListeners = new ArrayList<AnimatorUpdateListener>();
830        }
831        mUpdateListeners.add(listener);
832    }
833
834    /**
835     * Removes all listeners from the set listening to frame updates for this animation.
836     */
837    public void removeAllUpdateListeners() {
838        if (mUpdateListeners == null) {
839            return;
840        }
841        mUpdateListeners.clear();
842        mUpdateListeners = null;
843    }
844
845    /**
846     * Removes a listener from the set listening to frame updates for this animation.
847     *
848     * @param listener the listener to be removed from the current set of update listeners
849     * for this animation.
850     */
851    public void removeUpdateListener(AnimatorUpdateListener listener) {
852        if (mUpdateListeners == null) {
853            return;
854        }
855        mUpdateListeners.remove(listener);
856        if (mUpdateListeners.size() == 0) {
857            mUpdateListeners = null;
858        }
859    }
860
861
862    /**
863     * The time interpolator used in calculating the elapsed fraction of this animation. The
864     * interpolator determines whether the animation runs with linear or non-linear motion,
865     * such as acceleration and deceleration. The default value is
866     * {@link android.view.animation.AccelerateDecelerateInterpolator}
867     *
868     * @param value the interpolator to be used by this animation
869     */
870    @Override
871    public void setInterpolator(TimeInterpolator value) {
872        if (value != null) {
873            mInterpolator = value;
874        }
875    }
876
877    /**
878     * Returns the timing interpolator that this ValueAnimator uses.
879     *
880     * @return The timing interpolator for this ValueAnimator.
881     */
882    public TimeInterpolator getInterpolator() {
883        return mInterpolator;
884    }
885
886    /**
887     * The type evaluator to be used when calculating the animated values of this animation.
888     * The system will automatically assign a float, int, or double evaluator based on the type
889     * of <code>startValue</code> and <code>endValue</code> in the constructor. But if these values
890     * are not one of these primitive types, or if different evaluation is desired (such as is
891     * necessary with int values that represent colors), a custom evaluator needs to be assigned.
892     * For example, when running an animation on color values, the {@link RGBEvaluator}
893     * should be used to get correct RGB color interpolation.
894     *
895     * <p>If this ValueAnimator has only one set of values being animated between, this evaluator
896     * will be used for that set. If there are several sets of values being animated, which is
897     * the case if PropertyValuesHOlder objects were set on the ValueAnimator, then the evaluator
898     * is assigned just to the first PropertyValuesHolder object.</p>
899     *
900     * @param value the evaluator to be used this animation
901     */
902    public void setEvaluator(TypeEvaluator value) {
903        if (value != null && mValues != null && mValues.length > 0) {
904            mValues[0].setEvaluator(value);
905        }
906    }
907
908    /**
909     * Start the animation playing. This version of start() takes a boolean flag that indicates
910     * whether the animation should play in reverse. The flag is usually false, but may be set
911     * to true if called from the reverse() method/
912     *
913     * @param playBackwards Whether the ValueAnimator should start playing in reverse.
914     */
915    private void start(boolean playBackwards) {
916        mPlayingBackwards = playBackwards;
917        Looper looper = Looper.getMainLooper();
918        final boolean isUiThread;
919        if (looper != null) {
920            isUiThread = Thread.currentThread() == looper.getThread();
921        } else {
922            // ignore check if we don't have a Looper (this isn't an Activity)
923            isUiThread = true;
924        }
925        if ((mStartDelay == 0) && isUiThread) {
926            if (mListeners != null) {
927                ArrayList<AnimatorListener> tmpListeners =
928                        (ArrayList<AnimatorListener>) mListeners.clone();
929                for (AnimatorListener listener : tmpListeners) {
930                    listener.onAnimationStart(this);
931                }
932            }
933            // This sets the initial value of the animation, prior to actually starting it running
934            setCurrentPlayTime(getCurrentPlayTime());
935        }
936        mPlayingState = STOPPED;
937        mStartedDelay = false;
938        sPendingAnimations.add(this);
939        if (sAnimationHandler == null) {
940            sAnimationHandler = new AnimationHandler();
941        }
942        // TODO: does this put too many messages on the queue if the handler
943        // is already running?
944        sAnimationHandler.sendEmptyMessage(ANIMATION_START);
945    }
946
947    @Override
948    public void start() {
949        start(false);
950    }
951
952    @Override
953    public void cancel() {
954        if (mListeners != null) {
955            ArrayList<AnimatorListener> tmpListeners =
956                    (ArrayList<AnimatorListener>) mListeners.clone();
957            for (AnimatorListener listener : tmpListeners) {
958                listener.onAnimationCancel(this);
959            }
960        }
961        // Just set the CANCELED flag - this causes the animation to end the next time a frame
962        // is processed.
963        mPlayingState = CANCELED;
964    }
965
966    @Override
967    public void end() {
968        if (!sAnimations.contains(this) && !sPendingAnimations.contains(this)) {
969            // Special case if the animation has not yet started; get it ready for ending
970            mStartedDelay = false;
971            sPendingAnimations.add(this);
972            if (sAnimationHandler == null) {
973                sAnimationHandler = new AnimationHandler();
974            }
975            sAnimationHandler.sendEmptyMessage(ANIMATION_START);
976        }
977        // Just set the ENDED flag - this causes the animation to end the next time a frame
978        // is processed.
979        mPlayingState = ENDED;
980    }
981
982    @Override
983    public boolean isRunning() {
984        // ENDED or CANCELED indicate that it has been ended or canceled, but not processed yet
985        return (mPlayingState == RUNNING || mPlayingState == ENDED || mPlayingState == CANCELED);
986    }
987
988    /**
989     * Plays the ValueAnimator in reverse. If the animation is already running,
990     * it will stop itself and play backwards from the point reached when reverse was called.
991     * If the animation is not currently running, then it will start from the end and
992     * play backwards. This behavior is only set for the current animation; future playing
993     * of the animation will use the default behavior of playing forward.
994     */
995    public void reverse() {
996        mPlayingBackwards = !mPlayingBackwards;
997        if (mPlayingState == RUNNING) {
998            long currentTime = AnimationUtils.currentAnimationTimeMillis();
999            long currentPlayTime = currentTime - mStartTime;
1000            long timeLeft = mDuration - currentPlayTime;
1001            mStartTime = currentTime - timeLeft;
1002        } else {
1003            start(true);
1004        }
1005    }
1006
1007    /**
1008     * Called internally to end an animation by removing it from the animations list. Must be
1009     * called on the UI thread.
1010     */
1011    private void endAnimation() {
1012        sAnimations.remove(this);
1013        mPlayingState = STOPPED;
1014        if (mListeners != null) {
1015            ArrayList<AnimatorListener> tmpListeners =
1016                    (ArrayList<AnimatorListener>) mListeners.clone();
1017            for (AnimatorListener listener : tmpListeners) {
1018                listener.onAnimationEnd(this);
1019            }
1020        }
1021    }
1022
1023    /**
1024     * Called internally to start an animation by adding it to the active animations list. Must be
1025     * called on the UI thread.
1026     */
1027    private void startAnimation() {
1028        initAnimation();
1029        sAnimations.add(this);
1030        if (mStartDelay > 0 && mListeners != null) {
1031            // Listeners were already notified in start() if startDelay is 0; this is
1032            // just for delayed animations
1033            ArrayList<AnimatorListener> tmpListeners =
1034                    (ArrayList<AnimatorListener>) mListeners.clone();
1035            for (AnimatorListener listener : tmpListeners) {
1036                listener.onAnimationStart(this);
1037            }
1038        }
1039    }
1040
1041    /**
1042     * Internal function called to process an animation frame on an animation that is currently
1043     * sleeping through its <code>startDelay</code> phase. The return value indicates whether it
1044     * should be woken up and put on the active animations queue.
1045     *
1046     * @param currentTime The current animation time, used to calculate whether the animation
1047     * has exceeded its <code>startDelay</code> and should be started.
1048     * @return True if the animation's <code>startDelay</code> has been exceeded and the animation
1049     * should be added to the set of active animations.
1050     */
1051    private boolean delayedAnimationFrame(long currentTime) {
1052        if (mPlayingState == CANCELED || mPlayingState == ENDED) {
1053            // end the delay, process an animation frame to actually cancel it
1054            return true;
1055        }
1056        if (!mStartedDelay) {
1057            mStartedDelay = true;
1058            mDelayStartTime = currentTime;
1059        } else {
1060            long deltaTime = currentTime - mDelayStartTime;
1061            if (deltaTime > mStartDelay) {
1062                // startDelay ended - start the anim and record the
1063                // mStartTime appropriately
1064                mStartTime = currentTime - (deltaTime - mStartDelay);
1065                mPlayingState = RUNNING;
1066                return true;
1067            }
1068        }
1069        return false;
1070    }
1071
1072    /**
1073     * This internal function processes a single animation frame for a given animation. The
1074     * currentTime parameter is the timing pulse sent by the handler, used to calculate the
1075     * elapsed duration, and therefore
1076     * the elapsed fraction, of the animation. The return value indicates whether the animation
1077     * should be ended (which happens when the elapsed time of the animation exceeds the
1078     * animation's duration, including the repeatCount).
1079     *
1080     * @param currentTime The current time, as tracked by the static timing handler
1081     * @return true if the animation's duration, including any repetitions due to
1082     * <code>repeatCount</code> has been exceeded and the animation should be ended.
1083     */
1084    private boolean animationFrame(long currentTime) {
1085        boolean done = false;
1086
1087        if (mPlayingState == STOPPED) {
1088            mPlayingState = RUNNING;
1089            if (mSeekTime < 0) {
1090                mStartTime = currentTime;
1091            } else {
1092                mStartTime = currentTime - mSeekTime;
1093                // Now that we're playing, reset the seek time
1094                mSeekTime = -1;
1095            }
1096        }
1097        switch (mPlayingState) {
1098        case RUNNING:
1099        case SEEKED:
1100            float fraction = (float)(currentTime - mStartTime) / mDuration;
1101            if (fraction >= 1f) {
1102                if (mCurrentIteration < mRepeatCount || mRepeatCount == INFINITE) {
1103                    // Time to repeat
1104                    if (mListeners != null) {
1105                        for (AnimatorListener listener : mListeners) {
1106                            listener.onAnimationRepeat(this);
1107                        }
1108                    }
1109                    ++mCurrentIteration;
1110                    if (mRepeatMode == REVERSE) {
1111                        mPlayingBackwards = mPlayingBackwards ? false : true;
1112                    }
1113                    // TODO: doesn't account for fraction going Wayyyyy over 1, like 2+
1114                    fraction = fraction - 1f;
1115                    mStartTime += mDuration;
1116                } else {
1117                    done = true;
1118                    fraction = Math.min(fraction, 1.0f);
1119                }
1120            }
1121            if (mPlayingBackwards) {
1122                fraction = 1f - fraction;
1123            }
1124            animateValue(fraction);
1125            break;
1126        case ENDED:
1127            // The final value set on the target varies, depending on whether the animation
1128            // was supposed to repeat an odd number of times
1129            if (mRepeatCount > 0 && (mRepeatCount & 0x01) == 1) {
1130                animateValue(0f);
1131            } else {
1132                animateValue(1f);
1133            }
1134            // Fall through to set done flag
1135        case CANCELED:
1136            done = true;
1137            mPlayingState = STOPPED;
1138            break;
1139        }
1140
1141        return done;
1142    }
1143
1144    /**
1145     * This method is called with the elapsed fraction of the animation during every
1146     * animation frame. This function turns the elapsed fraction into an interpolated fraction
1147     * and then into an animated value (from the evaluator. The function is called mostly during
1148     * animation updates, but it is also called when the <code>end()</code>
1149     * function is called, to set the final value on the property.
1150     *
1151     * <p>Overrides of this method must call the superclass to perform the calculation
1152     * of the animated value.</p>
1153     *
1154     * @param fraction The elapsed fraction of the animation.
1155     */
1156    void animateValue(float fraction) {
1157        fraction = mInterpolator.getInterpolation(fraction);
1158        int numValues = mValues.length;
1159        for (int i = 0; i < numValues; ++i) {
1160            mValues[i].calculateValue(fraction);
1161        }
1162        if (mUpdateListeners != null) {
1163            int numListeners = mUpdateListeners.size();
1164            for (int i = 0; i < numListeners; ++i) {
1165                mUpdateListeners.get(i).onAnimationUpdate(this);
1166            }
1167        }
1168    }
1169
1170    @Override
1171    public ValueAnimator clone() {
1172        final ValueAnimator anim = (ValueAnimator) super.clone();
1173        if (mUpdateListeners != null) {
1174            ArrayList<AnimatorUpdateListener> oldListeners = mUpdateListeners;
1175            anim.mUpdateListeners = new ArrayList<AnimatorUpdateListener>();
1176            int numListeners = oldListeners.size();
1177            for (int i = 0; i < numListeners; ++i) {
1178                anim.mUpdateListeners.add(oldListeners.get(i));
1179            }
1180        }
1181        anim.mSeekTime = -1;
1182        anim.mPlayingBackwards = false;
1183        anim.mCurrentIteration = 0;
1184        anim.mInitialized = false;
1185        anim.mPlayingState = STOPPED;
1186        anim.mStartedDelay = false;
1187        PropertyValuesHolder[] oldValues = mValues;
1188        if (oldValues != null) {
1189            int numValues = oldValues.length;
1190            anim.mValues = new PropertyValuesHolder[numValues];
1191            for (int i = 0; i < numValues; ++i) {
1192                anim.mValues[i] = oldValues[i].clone();
1193            }
1194            anim.mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues);
1195            for (int i = 0; i < numValues; ++i) {
1196                PropertyValuesHolder valuesHolder = mValues[i];
1197                anim.mValuesMap.put(valuesHolder.getPropertyName(), valuesHolder);
1198            }
1199        }
1200        return anim;
1201    }
1202
1203    /**
1204     * Implementors of this interface can add themselves as update listeners
1205     * to an <code>ValueAnimator</code> instance to receive callbacks on every animation
1206     * frame, after the current frame's values have been calculated for that
1207     * <code>ValueAnimator</code>.
1208     */
1209    public static interface AnimatorUpdateListener {
1210        /**
1211         * <p>Notifies the occurrence of another frame of the animation.</p>
1212         *
1213         * @param animation The animation which was repeated.
1214         */
1215        void onAnimationUpdate(ValueAnimator animation);
1216
1217    }
1218}