ValueAnimator.java revision 599ca29986235e07f532c7b112507f6c39b5dba9
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            mInitialized = true;
527        }
528    }
529
530
531    /**
532     * Sets the length of the animation. The default duration is 300 milliseconds.
533     *
534     * @param duration The length of the animation, in milliseconds.
535     * @return ValueAnimator The object called with setDuration(). This return
536     * value makes it easier to compose statements together that construct and then set the
537     * duration, as in <code>ValueAnimator.ofInt(0, 10).setDuration(500).start()</code>.
538     */
539    public ValueAnimator setDuration(long duration) {
540        mDuration = duration;
541        return this;
542    }
543
544    /**
545     * Gets the length of the animation. The default duration is 300 milliseconds.
546     *
547     * @return The length of the animation, in milliseconds.
548     */
549    public long getDuration() {
550        return mDuration;
551    }
552
553    /**
554     * Sets the position of the animation to the specified point in time. This time should
555     * be between 0 and the total duration of the animation, including any repetition. If
556     * the animation has not yet been started, then it will not advance forward after it is
557     * set to this time; it will simply set the time to this value and perform any appropriate
558     * actions based on that time. If the animation is already running, then setCurrentPlayTime()
559     * will set the current playing time to this value and continue playing from that point.
560     *
561     * @param playTime The time, in milliseconds, to which the animation is advanced or rewound.
562     */
563    public void setCurrentPlayTime(long playTime) {
564        initAnimation();
565        long currentTime = AnimationUtils.currentAnimationTimeMillis();
566        if (mPlayingState != RUNNING) {
567            mSeekTime = playTime;
568            mPlayingState = SEEKED;
569        }
570        mStartTime = currentTime - playTime;
571        animationFrame(currentTime);
572    }
573
574    /**
575     * Gets the current position of the animation in time, which is equal to the current
576     * time minus the time that the animation started. An animation that is not yet started will
577     * return a value of zero.
578     *
579     * @return The current position in time of the animation.
580     */
581    public long getCurrentPlayTime() {
582        if (!mInitialized || mPlayingState == STOPPED) {
583            return 0;
584        }
585        return AnimationUtils.currentAnimationTimeMillis() - mStartTime;
586    }
587
588    /**
589     * This custom, static handler handles the timing pulse that is shared by
590     * all active animations. This approach ensures that the setting of animation
591     * values will happen on the UI thread and that all animations will share
592     * the same times for calculating their values, which makes synchronizing
593     * animations possible.
594     *
595     */
596    private static class AnimationHandler extends Handler {
597        /**
598         * There are only two messages that we care about: ANIMATION_START and
599         * ANIMATION_FRAME. The START message is sent when an animation's start()
600         * method is called. It cannot start synchronously when start() is called
601         * because the call may be on the wrong thread, and it would also not be
602         * synchronized with other animations because it would not start on a common
603         * timing pulse. So each animation sends a START message to the handler, which
604         * causes the handler to place the animation on the active animations queue and
605         * start processing frames for that animation.
606         * The FRAME message is the one that is sent over and over while there are any
607         * active animations to process.
608         */
609        @Override
610        public void handleMessage(Message msg) {
611            boolean callAgain = true;
612            switch (msg.what) {
613                // TODO: should we avoid sending frame message when starting if we
614                // were already running?
615                case ANIMATION_START:
616                    if (sAnimations.size() > 0 || sDelayedAnims.size() > 0) {
617                        callAgain = false;
618                    }
619                    // pendingAnims holds any animations that have requested to be started
620                    // We're going to clear sPendingAnimations, but starting animation may
621                    // cause more to be added to the pending list (for example, if one animation
622                    // starting triggers another starting). So we loop until sPendingAnimations
623                    // is empty.
624                    while (sPendingAnimations.size() > 0) {
625                        ArrayList<ValueAnimator> pendingCopy =
626                                (ArrayList<ValueAnimator>) sPendingAnimations.clone();
627                        sPendingAnimations.clear();
628                        int count = pendingCopy.size();
629                        for (int i = 0; i < count; ++i) {
630                            ValueAnimator anim = pendingCopy.get(i);
631                            // If the animation has a startDelay, place it on the delayed list
632                            if (anim.mStartDelay == 0 || anim.mPlayingState == ENDED ||
633                                    anim.mPlayingState == CANCELED) {
634                                anim.startAnimation();
635                            } else {
636                                sDelayedAnims.add(anim);
637                            }
638                        }
639                    }
640                    // fall through to process first frame of new animations
641                case ANIMATION_FRAME:
642                    // currentTime holds the common time for all animations processed
643                    // during this frame
644                    long currentTime = AnimationUtils.currentAnimationTimeMillis();
645
646                    // First, process animations currently sitting on the delayed queue, adding
647                    // them to the active animations if they are ready
648                    int numDelayedAnims = sDelayedAnims.size();
649                    for (int i = 0; i < numDelayedAnims; ++i) {
650                        ValueAnimator anim = sDelayedAnims.get(i);
651                        if (anim.delayedAnimationFrame(currentTime)) {
652                            sReadyAnims.add(anim);
653                        }
654                    }
655                    int numReadyAnims = sReadyAnims.size();
656                    if (numReadyAnims > 0) {
657                        for (int i = 0; i < numReadyAnims; ++i) {
658                            ValueAnimator anim = sReadyAnims.get(i);
659                            anim.startAnimation();
660                            sDelayedAnims.remove(anim);
661                        }
662                        sReadyAnims.clear();
663                    }
664
665                    // Now process all active animations. The return value from animationFrame()
666                    // tells the handler whether it should now be ended
667                    int numAnims = sAnimations.size();
668                    for (int i = 0; i < numAnims; ++i) {
669                        ValueAnimator anim = sAnimations.get(i);
670                        if (anim.animationFrame(currentTime)) {
671                            sEndingAnims.add(anim);
672                        }
673                    }
674                    if (sEndingAnims.size() > 0) {
675                        for (int i = 0; i < sEndingAnims.size(); ++i) {
676                            sEndingAnims.get(i).endAnimation();
677                        }
678                        sEndingAnims.clear();
679                    }
680
681                    // If there are still active or delayed animations, call the handler again
682                    // after the frameDelay
683                    if (callAgain && (!sAnimations.isEmpty() || !sDelayedAnims.isEmpty())) {
684                        sendEmptyMessageDelayed(ANIMATION_FRAME, Math.max(0, sFrameDelay -
685                            (AnimationUtils.currentAnimationTimeMillis() - currentTime)));
686                    }
687                    break;
688            }
689        }
690    }
691
692    /**
693     * The amount of time, in milliseconds, to delay starting the animation after
694     * {@link #start()} is called.
695     *
696     * @return the number of milliseconds to delay running the animation
697     */
698    public long getStartDelay() {
699        return mStartDelay;
700    }
701
702    /**
703     * The amount of time, in milliseconds, to delay starting the animation after
704     * {@link #start()} is called.
705
706     * @param startDelay The amount of the delay, in milliseconds
707     */
708    public void setStartDelay(long startDelay) {
709        this.mStartDelay = startDelay;
710    }
711
712    /**
713     * The amount of time, in milliseconds, between each frame of the animation. This is a
714     * requested time that the animation will attempt to honor, but the actual delay between
715     * frames may be different, depending on system load and capabilities. This is a static
716     * function because the same delay will be applied to all animations, since they are all
717     * run off of a single timing loop.
718     *
719     * @return the requested time between frames, in milliseconds
720     */
721    public static long getFrameDelay() {
722        return sFrameDelay;
723    }
724
725    /**
726     * The amount of time, in milliseconds, between each frame of the animation. This is a
727     * requested time that the animation will attempt to honor, but the actual delay between
728     * frames may be different, depending on system load and capabilities. This is a static
729     * function because the same delay will be applied to all animations, since they are all
730     * run off of a single timing loop.
731     *
732     * @param frameDelay the requested time between frames, in milliseconds
733     */
734    public static void setFrameDelay(long frameDelay) {
735        sFrameDelay = frameDelay;
736    }
737
738    /**
739     * The most recent value calculated by this <code>ValueAnimator</code> when there is just one
740     * property being animated. This value is only sensible while the animation is running. The main
741     * purpose for this read-only property is to retrieve the value from the <code>ValueAnimator</code>
742     * during a call to {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
743     * is called during each animation frame, immediately after the value is calculated.
744     *
745     * @return animatedValue The value most recently calculated by this <code>ValueAnimator</code> for
746     * the single property being animated. If there are several properties being animated
747     * (specified by several PropertyValuesHolder objects in the constructor), this function
748     * returns the animated value for the first of those objects.
749     */
750    public Object getAnimatedValue() {
751        if (mValues != null && mValues.length > 0) {
752            return mValues[0].getAnimatedValue();
753        }
754        // Shouldn't get here; should always have values unless ValueAnimator was set up wrong
755        return null;
756    }
757
758    /**
759     * The most recent value calculated by this <code>ValueAnimator</code> for <code>propertyName</code>.
760     * The main purpose for this read-only property is to retrieve the value from the
761     * <code>ValueAnimator</code> during a call to
762     * {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
763     * is called during each animation frame, immediately after the value is calculated.
764     *
765     * @return animatedValue The value most recently calculated for the named property
766     * by this <code>ValueAnimator</code>.
767     */
768    public Object getAnimatedValue(String propertyName) {
769        PropertyValuesHolder valuesHolder = mValuesMap.get(propertyName);
770        if (valuesHolder != null) {
771            return valuesHolder.getAnimatedValue();
772        } else {
773            // At least avoid crashing if called with bogus propertyName
774            return null;
775        }
776    }
777
778    /**
779     * Sets how many times the animation should be repeated. If the repeat
780     * count is 0, the animation is never repeated. If the repeat count is
781     * greater than 0 or {@link #INFINITE}, the repeat mode will be taken
782     * into account. The repeat count is 0 by default.
783     *
784     * @param value the number of times the animation should be repeated
785     */
786    public void setRepeatCount(int value) {
787        mRepeatCount = value;
788    }
789    /**
790     * Defines how many times the animation should repeat. The default value
791     * is 0.
792     *
793     * @return the number of times the animation should repeat, or {@link #INFINITE}
794     */
795    public int getRepeatCount() {
796        return mRepeatCount;
797    }
798
799    /**
800     * Defines what this animation should do when it reaches the end. This
801     * setting is applied only when the repeat count is either greater than
802     * 0 or {@link #INFINITE}. Defaults to {@link #RESTART}.
803     *
804     * @param value {@link #RESTART} or {@link #REVERSE}
805     */
806    public void setRepeatMode(int value) {
807        mRepeatMode = value;
808    }
809
810    /**
811     * Defines what this animation should do when it reaches the end.
812     *
813     * @return either one of {@link #REVERSE} or {@link #RESTART}
814     */
815    public int getRepeatMode() {
816        return mRepeatMode;
817    }
818
819    /**
820     * Adds a listener to the set of listeners that are sent update events through the life of
821     * an animation. This method is called on all listeners for every frame of the animation,
822     * after the values for the animation have been calculated.
823     *
824     * @param listener the listener to be added to the current set of listeners for this animation.
825     */
826    public void addUpdateListener(AnimatorUpdateListener listener) {
827        if (mUpdateListeners == null) {
828            mUpdateListeners = new ArrayList<AnimatorUpdateListener>();
829        }
830        mUpdateListeners.add(listener);
831    }
832
833    /**
834     * Removes all listeners from the set listening to frame updates for this animation.
835     */
836    public void removeAllUpdateListeners() {
837        if (mUpdateListeners == null) {
838            return;
839        }
840        mUpdateListeners.clear();
841        mUpdateListeners = null;
842    }
843
844    /**
845     * Removes a listener from the set listening to frame updates for this animation.
846     *
847     * @param listener the listener to be removed from the current set of update listeners
848     * for this animation.
849     */
850    public void removeUpdateListener(AnimatorUpdateListener listener) {
851        if (mUpdateListeners == null) {
852            return;
853        }
854        mUpdateListeners.remove(listener);
855        if (mUpdateListeners.size() == 0) {
856            mUpdateListeners = null;
857        }
858    }
859
860
861    /**
862     * The time interpolator used in calculating the elapsed fraction of this animation. The
863     * interpolator determines whether the animation runs with linear or non-linear motion,
864     * such as acceleration and deceleration. The default value is
865     * {@link android.view.animation.AccelerateDecelerateInterpolator}
866     *
867     * @param value the interpolator to be used by this animation
868     */
869    @Override
870    public void setInterpolator(TimeInterpolator value) {
871        if (value != null) {
872            mInterpolator = value;
873        }
874    }
875
876    /**
877     * Returns the timing interpolator that this ValueAnimator uses.
878     *
879     * @return The timing interpolator for this ValueAnimator.
880     */
881    public TimeInterpolator getInterpolator() {
882        return mInterpolator;
883    }
884
885    /**
886     * The type evaluator to be used when calculating the animated values of this animation.
887     * The system will automatically assign a float, int, or double evaluator based on the type
888     * of <code>startValue</code> and <code>endValue</code> in the constructor. But if these values
889     * are not one of these primitive types, or if different evaluation is desired (such as is
890     * necessary with int values that represent colors), a custom evaluator needs to be assigned.
891     * For example, when running an animation on color values, the {@link RGBEvaluator}
892     * should be used to get correct RGB color interpolation.
893     *
894     * <p>If this ValueAnimator has only one set of values being animated between, this evaluator
895     * will be used for that set. If there are several sets of values being animated, which is
896     * the case if PropertyValuesHOlder objects were set on the ValueAnimator, then the evaluator
897     * is assigned just to the first PropertyValuesHolder object.</p>
898     *
899     * @param value the evaluator to be used this animation
900     */
901    public void setEvaluator(TypeEvaluator value) {
902        if (value != null && mValues != null && mValues.length > 0) {
903            mValues[0].setEvaluator(value);
904        }
905    }
906
907    /**
908     * Start the animation playing. This version of start() takes a boolean flag that indicates
909     * whether the animation should play in reverse. The flag is usually false, but may be set
910     * to true if called from the reverse() method/
911     *
912     * @param playBackwards Whether the ValueAnimator should start playing in reverse.
913     */
914    private void start(boolean playBackwards) {
915        mPlayingBackwards = playBackwards;
916        Looper looper = Looper.getMainLooper();
917        final boolean isUiThread;
918        if (looper != null) {
919            isUiThread = Thread.currentThread() == looper.getThread();
920        } else {
921            // ignore check if we don't have a Looper (this isn't an Activity)
922            isUiThread = true;
923        }
924        if ((mStartDelay == 0) && isUiThread) {
925            if (mListeners != null) {
926                ArrayList<AnimatorListener> tmpListeners =
927                        (ArrayList<AnimatorListener>) mListeners.clone();
928                for (AnimatorListener listener : tmpListeners) {
929                    listener.onAnimationStart(this);
930                }
931            }
932            // This sets the initial value of the animation, prior to actually starting it running
933            setCurrentPlayTime(getCurrentPlayTime());
934        }
935        mCurrentIteration = 0;
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
1219    /**
1220     * Return the number of animations currently running.
1221     *
1222     * Used by StrictMode internally to annotate violations.  Only
1223     * called on the main thread.
1224     *
1225     * @hide
1226     */
1227    public static int getCurrentAnimationsCount() {
1228        return sAnimations.size();
1229    }
1230}
1231