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