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