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