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