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