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