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