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