ValueAnimator.java revision 7ae9d5faad5816f7e567ec1ec77e78d746cf7e5c
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 implements Runnable {
526        // The per-thread list of all active animations
527        private final ArrayList<ValueAnimator> mAnimations = new ArrayList<ValueAnimator>();
528
529        // The per-thread set of animations to be started on the next animation frame
530        private final ArrayList<ValueAnimator> mPendingAnimations = new ArrayList<ValueAnimator>();
531
532        /**
533         * Internal per-thread collections used to avoid set collisions as animations start and end
534         * while being processed.
535         */
536        private final ArrayList<ValueAnimator> mDelayedAnims = new ArrayList<ValueAnimator>();
537        private final ArrayList<ValueAnimator> mEndingAnims = new ArrayList<ValueAnimator>();
538        private final ArrayList<ValueAnimator> mReadyAnims = new ArrayList<ValueAnimator>();
539
540        private final Choreographer mChoreographer;
541        private boolean mAnimationScheduled;
542
543        private AnimationHandler() {
544            mChoreographer = Choreographer.getInstance();
545        }
546
547        /**
548         * The START message is sent when an animation's start()  method is called.
549         * It cannot start synchronously when start() is called
550         * because the call may be on the wrong thread, and it would also not be
551         * synchronized with other animations because it would not start on a common
552         * timing pulse. So each animation sends a START message to the handler, which
553         * causes the handler to place the animation on the active animations queue and
554         * start processing frames for that animation.
555         */
556        @Override
557        public void handleMessage(Message msg) {
558            switch (msg.what) {
559                case ANIMATION_START:
560                    doAnimationStart();
561                    break;
562            }
563        }
564
565        private void doAnimationStart() {
566            // mPendingAnimations holds any animations that have requested to be started
567            // We're going to clear mPendingAnimations, but starting animation may
568            // cause more to be added to the pending list (for example, if one animation
569            // starting triggers another starting). So we loop until mPendingAnimations
570            // is empty.
571            while (mPendingAnimations.size() > 0) {
572                ArrayList<ValueAnimator> pendingCopy =
573                        (ArrayList<ValueAnimator>) mPendingAnimations.clone();
574                mPendingAnimations.clear();
575                int count = pendingCopy.size();
576                for (int i = 0; i < count; ++i) {
577                    ValueAnimator anim = pendingCopy.get(i);
578                    // If the animation has a startDelay, place it on the delayed list
579                    if (anim.mStartDelay == 0) {
580                        anim.startAnimation(this);
581                    } else {
582                        mDelayedAnims.add(anim);
583                    }
584                }
585            }
586            doAnimationFrame();
587        }
588
589        private void doAnimationFrame() {
590            // currentTime holds the common time for all animations processed
591            // during this frame
592            long currentTime = AnimationUtils.currentAnimationTimeMillis();
593
594            // First, process animations currently sitting on the delayed queue, adding
595            // them to the active animations if they are ready
596            int numDelayedAnims = mDelayedAnims.size();
597            for (int i = 0; i < numDelayedAnims; ++i) {
598                ValueAnimator anim = mDelayedAnims.get(i);
599                if (anim.delayedAnimationFrame(currentTime)) {
600                    mReadyAnims.add(anim);
601                }
602            }
603            int numReadyAnims = mReadyAnims.size();
604            if (numReadyAnims > 0) {
605                for (int i = 0; i < numReadyAnims; ++i) {
606                    ValueAnimator anim = mReadyAnims.get(i);
607                    anim.startAnimation(this);
608                    anim.mRunning = true;
609                    mDelayedAnims.remove(anim);
610                }
611                mReadyAnims.clear();
612            }
613
614            // Now process all active animations. The return value from animationFrame()
615            // tells the handler whether it should now be ended
616            int numAnims = mAnimations.size();
617            int i = 0;
618            while (i < numAnims) {
619                ValueAnimator anim = mAnimations.get(i);
620                if (anim.animationFrame(currentTime)) {
621                    mEndingAnims.add(anim);
622                }
623                if (mAnimations.size() == numAnims) {
624                    ++i;
625                } else {
626                    // An animation might be canceled or ended by client code
627                    // during the animation frame. Check to see if this happened by
628                    // seeing whether the current index is the same as it was before
629                    // calling animationFrame(). Another approach would be to copy
630                    // animations to a temporary list and process that list instead,
631                    // but that entails garbage and processing overhead that would
632                    // be nice to avoid.
633                    --numAnims;
634                    mEndingAnims.remove(anim);
635                }
636            }
637            if (mEndingAnims.size() > 0) {
638                for (i = 0; i < mEndingAnims.size(); ++i) {
639                    mEndingAnims.get(i).endAnimation(this);
640                }
641                mEndingAnims.clear();
642            }
643
644            // If there are still active or delayed animations, schedule a future call to
645            // onAnimate to process the next frame of the animations.
646            if (!mAnimationScheduled
647                    && (!mAnimations.isEmpty() || !mDelayedAnims.isEmpty())) {
648                mChoreographer.postAnimationCallback(this, null);
649                mAnimationScheduled = true;
650            }
651        }
652
653        // Called by the Choreographer.
654        @Override
655        public void run() {
656            mAnimationScheduled = false;
657            doAnimationFrame();
658        }
659    }
660
661    /**
662     * The amount of time, in milliseconds, to delay starting the animation after
663     * {@link #start()} is called.
664     *
665     * @return the number of milliseconds to delay running the animation
666     */
667    public long getStartDelay() {
668        return mUnscaledStartDelay;
669    }
670
671    /**
672     * The amount of time, in milliseconds, to delay starting the animation after
673     * {@link #start()} is called.
674
675     * @param startDelay The amount of the delay, in milliseconds
676     */
677    public void setStartDelay(long startDelay) {
678        this.mStartDelay = (long)(startDelay * sDurationScale);
679        mUnscaledStartDelay = startDelay;
680    }
681
682    /**
683     * The amount of time, in milliseconds, between each frame of the animation. This is a
684     * requested time that the animation will attempt to honor, but the actual delay between
685     * frames may be different, depending on system load and capabilities. This is a static
686     * function because the same delay will be applied to all animations, since they are all
687     * run off of a single timing loop.
688     *
689     * The frame delay may be ignored when the animation system uses an external timing
690     * source, such as the display refresh rate (vsync), to govern animations.
691     *
692     * @return the requested time between frames, in milliseconds
693     */
694    public static long getFrameDelay() {
695        return Choreographer.getFrameDelay();
696    }
697
698    /**
699     * The amount of time, in milliseconds, between each frame of the animation. This is a
700     * requested time that the animation will attempt to honor, but the actual delay between
701     * frames may be different, depending on system load and capabilities. This is a static
702     * function because the same delay will be applied to all animations, since they are all
703     * run off of a single timing loop.
704     *
705     * The frame delay may be ignored when the animation system uses an external timing
706     * source, such as the display refresh rate (vsync), to govern animations.
707     *
708     * @param frameDelay the requested time between frames, in milliseconds
709     */
710    public static void setFrameDelay(long frameDelay) {
711        Choreographer.setFrameDelay(frameDelay);
712    }
713
714    /**
715     * The most recent value calculated by this <code>ValueAnimator</code> when there is just one
716     * property being animated. This value is only sensible while the animation is running. The main
717     * purpose for this read-only property is to retrieve the value from the <code>ValueAnimator</code>
718     * during a call to {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
719     * is called during each animation frame, immediately after the value is calculated.
720     *
721     * @return animatedValue The value most recently calculated by this <code>ValueAnimator</code> for
722     * the single property being animated. If there are several properties being animated
723     * (specified by several PropertyValuesHolder objects in the constructor), this function
724     * returns the animated value for the first of those objects.
725     */
726    public Object getAnimatedValue() {
727        if (mValues != null && mValues.length > 0) {
728            return mValues[0].getAnimatedValue();
729        }
730        // Shouldn't get here; should always have values unless ValueAnimator was set up wrong
731        return null;
732    }
733
734    /**
735     * The most recent value calculated by this <code>ValueAnimator</code> for <code>propertyName</code>.
736     * The main purpose for this read-only property is to retrieve the value from the
737     * <code>ValueAnimator</code> during a call to
738     * {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
739     * is called during each animation frame, immediately after the value is calculated.
740     *
741     * @return animatedValue The value most recently calculated for the named property
742     * by this <code>ValueAnimator</code>.
743     */
744    public Object getAnimatedValue(String propertyName) {
745        PropertyValuesHolder valuesHolder = mValuesMap.get(propertyName);
746        if (valuesHolder != null) {
747            return valuesHolder.getAnimatedValue();
748        } else {
749            // At least avoid crashing if called with bogus propertyName
750            return null;
751        }
752    }
753
754    /**
755     * Sets how many times the animation should be repeated. If the repeat
756     * count is 0, the animation is never repeated. If the repeat count is
757     * greater than 0 or {@link #INFINITE}, the repeat mode will be taken
758     * into account. The repeat count is 0 by default.
759     *
760     * @param value the number of times the animation should be repeated
761     */
762    public void setRepeatCount(int value) {
763        mRepeatCount = value;
764    }
765    /**
766     * Defines how many times the animation should repeat. The default value
767     * is 0.
768     *
769     * @return the number of times the animation should repeat, or {@link #INFINITE}
770     */
771    public int getRepeatCount() {
772        return mRepeatCount;
773    }
774
775    /**
776     * Defines what this animation should do when it reaches the end. This
777     * setting is applied only when the repeat count is either greater than
778     * 0 or {@link #INFINITE}. Defaults to {@link #RESTART}.
779     *
780     * @param value {@link #RESTART} or {@link #REVERSE}
781     */
782    public void setRepeatMode(int value) {
783        mRepeatMode = value;
784    }
785
786    /**
787     * Defines what this animation should do when it reaches the end.
788     *
789     * @return either one of {@link #REVERSE} or {@link #RESTART}
790     */
791    public int getRepeatMode() {
792        return mRepeatMode;
793    }
794
795    /**
796     * Adds a listener to the set of listeners that are sent update events through the life of
797     * an animation. This method is called on all listeners for every frame of the animation,
798     * after the values for the animation have been calculated.
799     *
800     * @param listener the listener to be added to the current set of listeners for this animation.
801     */
802    public void addUpdateListener(AnimatorUpdateListener listener) {
803        if (mUpdateListeners == null) {
804            mUpdateListeners = new ArrayList<AnimatorUpdateListener>();
805        }
806        mUpdateListeners.add(listener);
807    }
808
809    /**
810     * Removes all listeners from the set listening to frame updates for this animation.
811     */
812    public void removeAllUpdateListeners() {
813        if (mUpdateListeners == null) {
814            return;
815        }
816        mUpdateListeners.clear();
817        mUpdateListeners = null;
818    }
819
820    /**
821     * Removes a listener from the set listening to frame updates for this animation.
822     *
823     * @param listener the listener to be removed from the current set of update listeners
824     * for this animation.
825     */
826    public void removeUpdateListener(AnimatorUpdateListener listener) {
827        if (mUpdateListeners == null) {
828            return;
829        }
830        mUpdateListeners.remove(listener);
831        if (mUpdateListeners.size() == 0) {
832            mUpdateListeners = null;
833        }
834    }
835
836
837    /**
838     * The time interpolator used in calculating the elapsed fraction of this animation. The
839     * interpolator determines whether the animation runs with linear or non-linear motion,
840     * such as acceleration and deceleration. The default value is
841     * {@link android.view.animation.AccelerateDecelerateInterpolator}
842     *
843     * @param value the interpolator to be used by this animation. A value of <code>null</code>
844     * will result in linear interpolation.
845     */
846    @Override
847    public void setInterpolator(TimeInterpolator value) {
848        if (value != null) {
849            mInterpolator = value;
850        } else {
851            mInterpolator = new LinearInterpolator();
852        }
853    }
854
855    /**
856     * Returns the timing interpolator that this ValueAnimator uses.
857     *
858     * @return The timing interpolator for this ValueAnimator.
859     */
860    public TimeInterpolator getInterpolator() {
861        return mInterpolator;
862    }
863
864    /**
865     * The type evaluator to be used when calculating the animated values of this animation.
866     * The system will automatically assign a float or int evaluator based on the type
867     * of <code>startValue</code> and <code>endValue</code> in the constructor. But if these values
868     * are not one of these primitive types, or if different evaluation is desired (such as is
869     * necessary with int values that represent colors), a custom evaluator needs to be assigned.
870     * For example, when running an animation on color values, the {@link ArgbEvaluator}
871     * should be used to get correct RGB color interpolation.
872     *
873     * <p>If this ValueAnimator has only one set of values being animated between, this evaluator
874     * will be used for that set. If there are several sets of values being animated, which is
875     * the case if PropertyValuesHOlder objects were set on the ValueAnimator, then the evaluator
876     * is assigned just to the first PropertyValuesHolder object.</p>
877     *
878     * @param value the evaluator to be used this animation
879     */
880    public void setEvaluator(TypeEvaluator value) {
881        if (value != null && mValues != null && mValues.length > 0) {
882            mValues[0].setEvaluator(value);
883        }
884    }
885
886    /**
887     * Start the animation playing. This version of start() takes a boolean flag that indicates
888     * whether the animation should play in reverse. The flag is usually false, but may be set
889     * to true if called from the reverse() method.
890     *
891     * <p>The animation started by calling this method will be run on the thread that called
892     * this method. This thread should have a Looper on it (a runtime exception will be thrown if
893     * this is not the case). Also, if the animation will animate
894     * properties of objects in the view hierarchy, then the calling thread should be the UI
895     * thread for that view hierarchy.</p>
896     *
897     * @param playBackwards Whether the ValueAnimator should start playing in reverse.
898     */
899    private void start(boolean playBackwards) {
900        if (Looper.myLooper() == null) {
901            throw new AndroidRuntimeException("Animators may only be run on Looper threads");
902        }
903        mPlayingBackwards = playBackwards;
904        mCurrentIteration = 0;
905        mPlayingState = STOPPED;
906        mStarted = true;
907        mStartedDelay = false;
908        AnimationHandler animationHandler = getOrCreateAnimationHandler();
909        animationHandler.mPendingAnimations.add(this);
910        if (mStartDelay == 0) {
911            // This sets the initial value of the animation, prior to actually starting it running
912            setCurrentPlayTime(getCurrentPlayTime());
913            mPlayingState = STOPPED;
914            mRunning = true;
915
916            if (mListeners != null) {
917                ArrayList<AnimatorListener> tmpListeners =
918                        (ArrayList<AnimatorListener>) mListeners.clone();
919                int numListeners = tmpListeners.size();
920                for (int i = 0; i < numListeners; ++i) {
921                    tmpListeners.get(i).onAnimationStart(this);
922                }
923            }
924        }
925        animationHandler.sendEmptyMessage(ANIMATION_START);
926    }
927
928    @Override
929    public void start() {
930        start(false);
931    }
932
933    @Override
934    public void cancel() {
935        // Only cancel if the animation is actually running or has been started and is about
936        // to run
937        AnimationHandler handler = getOrCreateAnimationHandler();
938        if (mPlayingState != STOPPED
939                || handler.mPendingAnimations.contains(this)
940                || handler.mDelayedAnims.contains(this)) {
941            // Only notify listeners if the animator has actually started
942            if (mRunning && mListeners != null) {
943                ArrayList<AnimatorListener> tmpListeners =
944                        (ArrayList<AnimatorListener>) mListeners.clone();
945                for (AnimatorListener listener : tmpListeners) {
946                    listener.onAnimationCancel(this);
947                }
948            }
949            endAnimation(handler);
950        }
951    }
952
953    @Override
954    public void end() {
955        AnimationHandler handler = getOrCreateAnimationHandler();
956        if (!handler.mAnimations.contains(this) && !handler.mPendingAnimations.contains(this)) {
957            // Special case if the animation has not yet started; get it ready for ending
958            mStartedDelay = false;
959            startAnimation(handler);
960        } else if (!mInitialized) {
961            initAnimation();
962        }
963        // The final value set on the target varies, depending on whether the animation
964        // was supposed to repeat an odd number of times
965        if (mRepeatCount > 0 && (mRepeatCount & 0x01) == 1) {
966            animateValue(0f);
967        } else {
968            animateValue(1f);
969        }
970        endAnimation(handler);
971    }
972
973    @Override
974    public boolean isRunning() {
975        return (mPlayingState == RUNNING || mRunning);
976    }
977
978    @Override
979    public boolean isStarted() {
980        return mStarted;
981    }
982
983    /**
984     * Plays the ValueAnimator in reverse. If the animation is already running,
985     * it will stop itself and play backwards from the point reached when reverse was called.
986     * If the animation is not currently running, then it will start from the end and
987     * play backwards. This behavior is only set for the current animation; future playing
988     * of the animation will use the default behavior of playing forward.
989     */
990    public void reverse() {
991        mPlayingBackwards = !mPlayingBackwards;
992        if (mPlayingState == RUNNING) {
993            long currentTime = AnimationUtils.currentAnimationTimeMillis();
994            long currentPlayTime = currentTime - mStartTime;
995            long timeLeft = mDuration - currentPlayTime;
996            mStartTime = currentTime - timeLeft;
997        } else {
998            start(true);
999        }
1000    }
1001
1002    /**
1003     * Called internally to end an animation by removing it from the animations list. Must be
1004     * called on the UI thread.
1005     */
1006    private void endAnimation(AnimationHandler handler) {
1007        handler.mAnimations.remove(this);
1008        handler.mPendingAnimations.remove(this);
1009        handler.mDelayedAnims.remove(this);
1010        mPlayingState = STOPPED;
1011        if (mRunning && mListeners != null) {
1012            ArrayList<AnimatorListener> tmpListeners =
1013                    (ArrayList<AnimatorListener>) mListeners.clone();
1014            int numListeners = tmpListeners.size();
1015            for (int i = 0; i < numListeners; ++i) {
1016                tmpListeners.get(i).onAnimationEnd(this);
1017            }
1018        }
1019        mRunning = false;
1020        mStarted = false;
1021    }
1022
1023    /**
1024     * Called internally to start an animation by adding it to the active animations list. Must be
1025     * called on the UI thread.
1026     */
1027    private void startAnimation(AnimationHandler handler) {
1028        initAnimation();
1029        handler.mAnimations.add(this);
1030        if (mStartDelay > 0 && mListeners != null) {
1031            // Listeners were already notified in start() if startDelay is 0; this is
1032            // just for delayed animations
1033            ArrayList<AnimatorListener> tmpListeners =
1034                    (ArrayList<AnimatorListener>) mListeners.clone();
1035            int numListeners = tmpListeners.size();
1036            for (int i = 0; i < numListeners; ++i) {
1037                tmpListeners.get(i).onAnimationStart(this);
1038            }
1039        }
1040    }
1041
1042    /**
1043     * Internal function called to process an animation frame on an animation that is currently
1044     * sleeping through its <code>startDelay</code> phase. The return value indicates whether it
1045     * should be woken up and put on the active animations queue.
1046     *
1047     * @param currentTime The current animation time, used to calculate whether the animation
1048     * has exceeded its <code>startDelay</code> and should be started.
1049     * @return True if the animation's <code>startDelay</code> has been exceeded and the animation
1050     * should be added to the set of active animations.
1051     */
1052    private boolean delayedAnimationFrame(long currentTime) {
1053        if (!mStartedDelay) {
1054            mStartedDelay = true;
1055            mDelayStartTime = currentTime;
1056        } else {
1057            long deltaTime = currentTime - mDelayStartTime;
1058            if (deltaTime > mStartDelay) {
1059                // startDelay ended - start the anim and record the
1060                // mStartTime appropriately
1061                mStartTime = currentTime - (deltaTime - mStartDelay);
1062                mPlayingState = RUNNING;
1063                return true;
1064            }
1065        }
1066        return false;
1067    }
1068
1069    /**
1070     * This internal function processes a single animation frame for a given animation. The
1071     * currentTime parameter is the timing pulse sent by the handler, used to calculate the
1072     * elapsed duration, and therefore
1073     * the elapsed fraction, of the animation. The return value indicates whether the animation
1074     * should be ended (which happens when the elapsed time of the animation exceeds the
1075     * animation's duration, including the repeatCount).
1076     *
1077     * @param currentTime The current time, as tracked by the static timing handler
1078     * @return true if the animation's duration, including any repetitions due to
1079     * <code>repeatCount</code> has been exceeded and the animation should be ended.
1080     */
1081    boolean animationFrame(long currentTime) {
1082        boolean done = false;
1083
1084        if (mPlayingState == STOPPED) {
1085            mPlayingState = RUNNING;
1086            if (mSeekTime < 0) {
1087                mStartTime = currentTime;
1088            } else {
1089                mStartTime = currentTime - mSeekTime;
1090                // Now that we're playing, reset the seek time
1091                mSeekTime = -1;
1092            }
1093        }
1094        switch (mPlayingState) {
1095        case RUNNING:
1096        case SEEKED:
1097            float fraction = mDuration > 0 ? (float)(currentTime - mStartTime) / mDuration : 1f;
1098            if (fraction >= 1f) {
1099                if (mCurrentIteration < mRepeatCount || mRepeatCount == INFINITE) {
1100                    // Time to repeat
1101                    if (mListeners != null) {
1102                        int numListeners = mListeners.size();
1103                        for (int i = 0; i < numListeners; ++i) {
1104                            mListeners.get(i).onAnimationRepeat(this);
1105                        }
1106                    }
1107                    if (mRepeatMode == REVERSE) {
1108                        mPlayingBackwards = mPlayingBackwards ? false : true;
1109                    }
1110                    mCurrentIteration += (int)fraction;
1111                    fraction = fraction % 1f;
1112                    mStartTime += mDuration;
1113                } else {
1114                    done = true;
1115                    fraction = Math.min(fraction, 1.0f);
1116                }
1117            }
1118            if (mPlayingBackwards) {
1119                fraction = 1f - fraction;
1120            }
1121            animateValue(fraction);
1122            break;
1123        }
1124
1125        return done;
1126    }
1127
1128    /**
1129     * Returns the current animation fraction, which is the elapsed/interpolated fraction used in
1130     * the most recent frame update on the animation.
1131     *
1132     * @return Elapsed/interpolated fraction of the animation.
1133     */
1134    public float getAnimatedFraction() {
1135        return mCurrentFraction;
1136    }
1137
1138    /**
1139     * This method is called with the elapsed fraction of the animation during every
1140     * animation frame. This function turns the elapsed fraction into an interpolated fraction
1141     * and then into an animated value (from the evaluator. The function is called mostly during
1142     * animation updates, but it is also called when the <code>end()</code>
1143     * function is called, to set the final value on the property.
1144     *
1145     * <p>Overrides of this method must call the superclass to perform the calculation
1146     * of the animated value.</p>
1147     *
1148     * @param fraction The elapsed fraction of the animation.
1149     */
1150    void animateValue(float fraction) {
1151        fraction = mInterpolator.getInterpolation(fraction);
1152        mCurrentFraction = fraction;
1153        int numValues = mValues.length;
1154        for (int i = 0; i < numValues; ++i) {
1155            mValues[i].calculateValue(fraction);
1156        }
1157        if (mUpdateListeners != null) {
1158            int numListeners = mUpdateListeners.size();
1159            for (int i = 0; i < numListeners; ++i) {
1160                mUpdateListeners.get(i).onAnimationUpdate(this);
1161            }
1162        }
1163    }
1164
1165    @Override
1166    public ValueAnimator clone() {
1167        final ValueAnimator anim = (ValueAnimator) super.clone();
1168        if (mUpdateListeners != null) {
1169            ArrayList<AnimatorUpdateListener> oldListeners = mUpdateListeners;
1170            anim.mUpdateListeners = new ArrayList<AnimatorUpdateListener>();
1171            int numListeners = oldListeners.size();
1172            for (int i = 0; i < numListeners; ++i) {
1173                anim.mUpdateListeners.add(oldListeners.get(i));
1174            }
1175        }
1176        anim.mSeekTime = -1;
1177        anim.mPlayingBackwards = false;
1178        anim.mCurrentIteration = 0;
1179        anim.mInitialized = false;
1180        anim.mPlayingState = STOPPED;
1181        anim.mStartedDelay = false;
1182        PropertyValuesHolder[] oldValues = mValues;
1183        if (oldValues != null) {
1184            int numValues = oldValues.length;
1185            anim.mValues = new PropertyValuesHolder[numValues];
1186            anim.mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues);
1187            for (int i = 0; i < numValues; ++i) {
1188                PropertyValuesHolder newValuesHolder = oldValues[i].clone();
1189                anim.mValues[i] = newValuesHolder;
1190                anim.mValuesMap.put(newValuesHolder.getPropertyName(), newValuesHolder);
1191            }
1192        }
1193        return anim;
1194    }
1195
1196    /**
1197     * Implementors of this interface can add themselves as update listeners
1198     * to an <code>ValueAnimator</code> instance to receive callbacks on every animation
1199     * frame, after the current frame's values have been calculated for that
1200     * <code>ValueAnimator</code>.
1201     */
1202    public static interface AnimatorUpdateListener {
1203        /**
1204         * <p>Notifies the occurrence of another frame of the animation.</p>
1205         *
1206         * @param animation The animation which was repeated.
1207         */
1208        void onAnimationUpdate(ValueAnimator animation);
1209
1210    }
1211
1212    /**
1213     * Return the number of animations currently running.
1214     *
1215     * Used by StrictMode internally to annotate violations.
1216     * May be called on arbitrary threads!
1217     *
1218     * @hide
1219     */
1220    public static int getCurrentAnimationsCount() {
1221        AnimationHandler handler = sAnimationHandler.get();
1222        return handler != null ? handler.mAnimations.size() : 0;
1223    }
1224
1225    /**
1226     * Clear all animations on this thread, without canceling or ending them.
1227     * This should be used with caution.
1228     *
1229     * @hide
1230     */
1231    public static void clearAllAnimations() {
1232        AnimationHandler handler = sAnimationHandler.get();
1233        if (handler != null) {
1234            handler.mAnimations.clear();
1235            handler.mPendingAnimations.clear();
1236            handler.mDelayedAnims.clear();
1237        }
1238    }
1239
1240    private AnimationHandler getOrCreateAnimationHandler() {
1241        AnimationHandler handler = sAnimationHandler.get();
1242        if (handler == null) {
1243            handler = new AnimationHandler();
1244            sAnimationHandler.set(handler);
1245        }
1246        return handler;
1247    }
1248
1249    @Override
1250    public String toString() {
1251        String returnVal = "ValueAnimator@" + Integer.toHexString(hashCode());
1252        if (mValues != null) {
1253            for (int i = 0; i < mValues.length; ++i) {
1254                returnVal += "\n    " + mValues[i].toString();
1255            }
1256        }
1257        return returnVal;
1258    }
1259}
1260