ValueAnimator.java revision 2ac6547824ff217a89b726fa633dfd60c6f7bd89
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.annotation.CallSuper;
20import android.annotation.IntDef;
21import android.annotation.TestApi;
22import android.os.Looper;
23import android.os.Trace;
24import android.util.AndroidRuntimeException;
25import android.util.Log;
26import android.view.animation.AccelerateDecelerateInterpolator;
27import android.view.animation.Animation;
28import android.view.animation.AnimationUtils;
29import android.view.animation.LinearInterpolator;
30
31import java.lang.annotation.Retention;
32import java.lang.annotation.RetentionPolicy;
33import java.util.ArrayList;
34import java.util.HashMap;
35
36/**
37 * This class provides a simple timing engine for running animations
38 * which calculate animated values and set them on target objects.
39 *
40 * <p>There is a single timing pulse that all animations use. It runs in a
41 * custom handler to ensure that property changes happen on the UI thread.</p>
42 *
43 * <p>By default, ValueAnimator uses non-linear time interpolation, via the
44 * {@link AccelerateDecelerateInterpolator} class, which accelerates into and decelerates
45 * out of an animation. This behavior can be changed by calling
46 * {@link ValueAnimator#setInterpolator(TimeInterpolator)}.</p>
47 *
48 * <p>Animators can be created from either code or resource files. Here is an example
49 * of a ValueAnimator resource file:</p>
50 *
51 * {@sample development/samples/ApiDemos/res/anim/animator.xml ValueAnimatorResources}
52 *
53 * <p>Starting from API 23, it is also possible to use a combination of {@link PropertyValuesHolder}
54 * and {@link Keyframe} resource tags to create a multi-step animation.
55 * Note that you can specify explicit fractional values (from 0 to 1) for
56 * each keyframe to determine when, in the overall duration, the animation should arrive at that
57 * value. Alternatively, you can leave the fractions off and the keyframes will be equally
58 * distributed within the total duration:</p>
59 *
60 * {@sample development/samples/ApiDemos/res/anim/value_animator_pvh_kf.xml
61 * ValueAnimatorKeyframeResources}
62 *
63 * <div class="special reference">
64 * <h3>Developer Guides</h3>
65 * <p>For more information about animating with {@code ValueAnimator}, read the
66 * <a href="{@docRoot}guide/topics/graphics/prop-animation.html#value-animator">Property
67 * Animation</a> developer guide.</p>
68 * </div>
69 */
70@SuppressWarnings("unchecked")
71public class ValueAnimator extends Animator implements AnimationHandler.AnimationFrameCallback {
72    private static final String TAG = "ValueAnimator";
73    private static final boolean DEBUG = false;
74
75    /**
76     * Internal constants
77     */
78    private static float sDurationScale = 1.0f;
79
80    /**
81     * Internal variables
82     * NOTE: This object implements the clone() method, making a deep copy of any referenced
83     * objects. As other non-trivial fields are added to this class, make sure to add logic
84     * to clone() to make deep copies of them.
85     */
86
87    /**
88     * The first time that the animation's animateFrame() method is called. This time is used to
89     * determine elapsed time (and therefore the elapsed fraction) in subsequent calls
90     * to animateFrame().
91     *
92     * Whenever mStartTime is set, you must also update mStartTimeCommitted.
93     */
94    long mStartTime = -1;
95
96    /**
97     * When true, the start time has been firmly committed as a chosen reference point in
98     * time by which the progress of the animation will be evaluated.  When false, the
99     * start time may be updated when the first animation frame is committed so as
100     * to compensate for jank that may have occurred between when the start time was
101     * initialized and when the frame was actually drawn.
102     *
103     * This flag is generally set to false during the first frame of the animation
104     * when the animation playing state transitions from STOPPED to RUNNING or
105     * resumes after having been paused.  This flag is set to true when the start time
106     * is firmly committed and should not be further compensated for jank.
107     */
108    boolean mStartTimeCommitted;
109
110    /**
111     * Set when setCurrentPlayTime() is called. If negative, animation is not currently seeked
112     * to a value.
113     */
114    float mSeekFraction = -1;
115
116    /**
117     * Set on the next frame after pause() is called, used to calculate a new startTime
118     * or delayStartTime which allows the animator to continue from the point at which
119     * it was paused. If negative, has not yet been set.
120     */
121    private long mPauseTime;
122
123    /**
124     * Set when an animator is resumed. This triggers logic in the next frame which
125     * actually resumes the animator.
126     */
127    private boolean mResumed = false;
128
129    // The time interpolator to be used if none is set on the animation
130    private static final TimeInterpolator sDefaultInterpolator =
131            new AccelerateDecelerateInterpolator();
132
133    /**
134     * Flag to indicate whether this animator is playing in reverse mode, specifically
135     * by being started or interrupted by a call to reverse(). This flag is different than
136     * mPlayingBackwards, which indicates merely whether the current iteration of the
137     * animator is playing in reverse. It is used in corner cases to determine proper end
138     * behavior.
139     */
140    private boolean mReversing;
141
142    /**
143     * Tracks the overall fraction of the animation, ranging from 0 to mRepeatCount + 1
144     */
145    private float mOverallFraction = 0f;
146
147    /**
148     * Tracks current elapsed/eased fraction, for querying in getAnimatedFraction().
149     * This is calculated by interpolating the fraction (range: [0, 1]) in the current iteration.
150     */
151    private float mCurrentFraction = 0f;
152
153    /**
154     * Tracks the time (in milliseconds) when the last frame arrived.
155     */
156    private long mLastFrameTime = -1;
157
158    /**
159     * Tracks the time (in milliseconds) when the first frame arrived. Note the frame may arrive
160     * during the start delay.
161     */
162    private long mFirstFrameTime = -1;
163
164    /**
165     * Additional playing state to indicate whether an animator has been start()'d. There is
166     * some lag between a call to start() and the first animation frame. We should still note
167     * that the animation has been started, even if it's first animation frame has not yet
168     * happened, and reflect that state in isRunning().
169     * Note that delayed animations are different: they are not started until their first
170     * animation frame, which occurs after their delay elapses.
171     */
172    private boolean mRunning = false;
173
174    /**
175     * Additional playing state to indicate whether an animator has been start()'d, whether or
176     * not there is a nonzero startDelay.
177     */
178    private boolean mStarted = false;
179
180    /**
181     * Tracks whether we've notified listeners of the onAnimationStart() event. This can be
182     * complex to keep track of since we notify listeners at different times depending on
183     * startDelay and whether start() was called before end().
184     */
185    private boolean mStartListenersCalled = false;
186
187    /**
188     * Flag that denotes whether the animation is set up and ready to go. Used to
189     * set up animation that has not yet been started.
190     */
191    boolean mInitialized = false;
192
193    /**
194     * Flag that tracks whether animation has been requested to end.
195     */
196    private boolean mAnimationEndRequested = false;
197
198    //
199    // Backing variables
200    //
201
202    // How long the animation should last in ms
203    private long mDuration = 300;
204
205    // The amount of time in ms to delay starting the animation after start() is called. Note
206    // that this start delay is unscaled. When there is a duration scale set on the animator, the
207    // scaling factor will be applied to this delay.
208    private long mStartDelay = 0;
209
210    // The number of times the animation will repeat. The default is 0, which means the animation
211    // will play only once
212    private int mRepeatCount = 0;
213
214    /**
215     * The type of repetition that will occur when repeatMode is nonzero. RESTART means the
216     * animation will start from the beginning on every new cycle. REVERSE means the animation
217     * will reverse directions on each iteration.
218     */
219    private int mRepeatMode = RESTART;
220
221    /**
222     * Whether or not the animator should register for its own animation callback to receive
223     * animation pulse.
224     */
225    private boolean mSelfPulse = true;
226
227    /**
228     * Whether or not the animator has been requested to start without pulsing. This flag gets set
229     * in startWithoutPulsing(), and reset in start().
230     */
231    private boolean mSuppressSelfPulseRequested = false;
232
233    /**
234     * The time interpolator to be used. The elapsed fraction of the animation will be passed
235     * through this interpolator to calculate the interpolated fraction, which is then used to
236     * calculate the animated values.
237     */
238    private TimeInterpolator mInterpolator = sDefaultInterpolator;
239
240    /**
241     * The set of listeners to be sent events through the life of an animation.
242     */
243    ArrayList<AnimatorUpdateListener> mUpdateListeners = null;
244
245    /**
246     * The property/value sets being animated.
247     */
248    PropertyValuesHolder[] mValues;
249
250    /**
251     * A hashmap of the PropertyValuesHolder objects. This map is used to lookup animated values
252     * by property name during calls to getAnimatedValue(String).
253     */
254    HashMap<String, PropertyValuesHolder> mValuesMap;
255
256    /**
257     * Public constants
258     */
259
260    /** @hide */
261    @IntDef({RESTART, REVERSE})
262    @Retention(RetentionPolicy.SOURCE)
263    public @interface RepeatMode {}
264
265    /**
266     * When the animation reaches the end and <code>repeatCount</code> is INFINITE
267     * or a positive value, the animation restarts from the beginning.
268     */
269    public static final int RESTART = 1;
270    /**
271     * When the animation reaches the end and <code>repeatCount</code> is INFINITE
272     * or a positive value, the animation reverses direction on every iteration.
273     */
274    public static final int REVERSE = 2;
275    /**
276     * This value used used with the {@link #setRepeatCount(int)} property to repeat
277     * the animation indefinitely.
278     */
279    public static final int INFINITE = -1;
280
281    /**
282     * @hide
283     */
284    @TestApi
285    public static void setDurationScale(float durationScale) {
286        sDurationScale = durationScale;
287    }
288
289    /**
290     * @hide
291     */
292    @TestApi
293    public static float getDurationScale() {
294        return sDurationScale;
295    }
296
297    /**
298     * Returns whether animators are currently enabled, system-wide. By default, all
299     * animators are enabled. This can change if either the user sets a Developer Option
300     * to set the animator duration scale to 0 or by Battery Savery mode being enabled
301     * (which disables all animations).
302     *
303     * <p>Developers should not typically need to call this method, but should an app wish
304     * to show a different experience when animators are disabled, this return value
305     * can be used as a decider of which experience to offer.
306     *
307     * @return boolean Whether animators are currently enabled. The default value is
308     * <code>true</code>.
309     */
310    public static boolean areAnimatorsEnabled() {
311        return !(sDurationScale == 0);
312    }
313
314    /**
315     * Creates a new ValueAnimator object. This default constructor is primarily for
316     * use internally; the factory methods which take parameters are more generally
317     * useful.
318     */
319    public ValueAnimator() {
320    }
321
322    /**
323     * Constructs and returns a ValueAnimator that animates between int values. A single
324     * value implies that that value is the one being animated to. However, this is not typically
325     * useful in a ValueAnimator object because there is no way for the object to determine the
326     * starting value for the animation (unlike ObjectAnimator, which can derive that value
327     * from the target object and property being animated). Therefore, there should typically
328     * be two or more values.
329     *
330     * @param values A set of values that the animation will animate between over time.
331     * @return A ValueAnimator object that is set up to animate between the given values.
332     */
333    public static ValueAnimator ofInt(int... values) {
334        ValueAnimator anim = new ValueAnimator();
335        anim.setIntValues(values);
336        return anim;
337    }
338
339    /**
340     * Constructs and returns a ValueAnimator that animates between color values. A single
341     * value implies that that value is the one being animated to. However, this is not typically
342     * useful in a ValueAnimator object because there is no way for the object to determine the
343     * starting value for the animation (unlike ObjectAnimator, which can derive that value
344     * from the target object and property being animated). Therefore, there should typically
345     * be two or more values.
346     *
347     * @param values A set of values that the animation will animate between over time.
348     * @return A ValueAnimator object that is set up to animate between the given values.
349     */
350    public static ValueAnimator ofArgb(int... values) {
351        ValueAnimator anim = new ValueAnimator();
352        anim.setIntValues(values);
353        anim.setEvaluator(ArgbEvaluator.getInstance());
354        return anim;
355    }
356
357    /**
358     * Constructs and returns a ValueAnimator that animates between float values. A single
359     * value implies that that value is the one being animated to. However, this is not typically
360     * useful in a ValueAnimator object because there is no way for the object to determine the
361     * starting value for the animation (unlike ObjectAnimator, which can derive that value
362     * from the target object and property being animated). Therefore, there should typically
363     * be two or more values.
364     *
365     * @param values A set of values that the animation will animate between over time.
366     * @return A ValueAnimator object that is set up to animate between the given values.
367     */
368    public static ValueAnimator ofFloat(float... values) {
369        ValueAnimator anim = new ValueAnimator();
370        anim.setFloatValues(values);
371        return anim;
372    }
373
374    /**
375     * Constructs and returns a ValueAnimator that animates between the values
376     * specified in the PropertyValuesHolder objects.
377     *
378     * @param values A set of PropertyValuesHolder objects whose values will be animated
379     * between over time.
380     * @return A ValueAnimator object that is set up to animate between the given values.
381     */
382    public static ValueAnimator ofPropertyValuesHolder(PropertyValuesHolder... values) {
383        ValueAnimator anim = new ValueAnimator();
384        anim.setValues(values);
385        return anim;
386    }
387    /**
388     * Constructs and returns a ValueAnimator that animates between Object values. A single
389     * value implies that that value is the one being animated to. However, this is not typically
390     * useful in a ValueAnimator object because there is no way for the object to determine the
391     * starting value for the animation (unlike ObjectAnimator, which can derive that value
392     * from the target object and property being animated). Therefore, there should typically
393     * be two or more values.
394     *
395     * <p><strong>Note:</strong> The Object values are stored as references to the original
396     * objects, which means that changes to those objects after this method is called will
397     * affect the values on the animator. If the objects will be mutated externally after
398     * this method is called, callers should pass a copy of those objects instead.
399     *
400     * <p>Since ValueAnimator does not know how to animate between arbitrary Objects, this
401     * factory method also takes a TypeEvaluator object that the ValueAnimator will use
402     * to perform that interpolation.
403     *
404     * @param evaluator A TypeEvaluator that will be called on each animation frame to
405     * provide the ncessry interpolation between the Object values to derive the animated
406     * value.
407     * @param values A set of values that the animation will animate between over time.
408     * @return A ValueAnimator object that is set up to animate between the given values.
409     */
410    public static ValueAnimator ofObject(TypeEvaluator evaluator, Object... values) {
411        ValueAnimator anim = new ValueAnimator();
412        anim.setObjectValues(values);
413        anim.setEvaluator(evaluator);
414        return anim;
415    }
416
417    /**
418     * Sets int values that will be animated between. A single
419     * value implies that that value is the one being animated to. However, this is not typically
420     * useful in a ValueAnimator object because there is no way for the object to determine the
421     * starting value for the animation (unlike ObjectAnimator, which can derive that value
422     * from the target object and property being animated). Therefore, there should typically
423     * be two or more values.
424     *
425     * <p>If there are already multiple sets of values defined for this ValueAnimator via more
426     * than one PropertyValuesHolder object, this method will set the values for the first
427     * of those objects.</p>
428     *
429     * @param values A set of values that the animation will animate between over time.
430     */
431    public void setIntValues(int... values) {
432        if (values == null || values.length == 0) {
433            return;
434        }
435        if (mValues == null || mValues.length == 0) {
436            setValues(PropertyValuesHolder.ofInt("", values));
437        } else {
438            PropertyValuesHolder valuesHolder = mValues[0];
439            valuesHolder.setIntValues(values);
440        }
441        // New property/values/target should cause re-initialization prior to starting
442        mInitialized = false;
443    }
444
445    /**
446     * Sets float values that will be animated between. A single
447     * value implies that that value is the one being animated to. However, this is not typically
448     * useful in a ValueAnimator object because there is no way for the object to determine the
449     * starting value for the animation (unlike ObjectAnimator, which can derive that value
450     * from the target object and property being animated). Therefore, there should typically
451     * be two or more values.
452     *
453     * <p>If there are already multiple sets of values defined for this ValueAnimator via more
454     * than one PropertyValuesHolder object, this method will set the values for the first
455     * of those objects.</p>
456     *
457     * @param values A set of values that the animation will animate between over time.
458     */
459    public void setFloatValues(float... values) {
460        if (values == null || values.length == 0) {
461            return;
462        }
463        if (mValues == null || mValues.length == 0) {
464            setValues(PropertyValuesHolder.ofFloat("", values));
465        } else {
466            PropertyValuesHolder valuesHolder = mValues[0];
467            valuesHolder.setFloatValues(values);
468        }
469        // New property/values/target should cause re-initialization prior to starting
470        mInitialized = false;
471    }
472
473    /**
474     * Sets the values to animate between for this animation. A single
475     * value implies that that value is the one being animated to. However, this is not typically
476     * useful in a ValueAnimator object because there is no way for the object to determine the
477     * starting value for the animation (unlike ObjectAnimator, which can derive that value
478     * from the target object and property being animated). Therefore, there should typically
479     * be two or more values.
480     *
481     * <p><strong>Note:</strong> The Object values are stored as references to the original
482     * objects, which means that changes to those objects after this method is called will
483     * affect the values on the animator. If the objects will be mutated externally after
484     * this method is called, callers should pass a copy of those objects instead.
485     *
486     * <p>If there are already multiple sets of values defined for this ValueAnimator via more
487     * than one PropertyValuesHolder object, this method will set the values for the first
488     * of those objects.</p>
489     *
490     * <p>There should be a TypeEvaluator set on the ValueAnimator that knows how to interpolate
491     * between these value objects. ValueAnimator only knows how to interpolate between the
492     * primitive types specified in the other setValues() methods.</p>
493     *
494     * @param values The set of values to animate between.
495     */
496    public void setObjectValues(Object... values) {
497        if (values == null || values.length == 0) {
498            return;
499        }
500        if (mValues == null || mValues.length == 0) {
501            setValues(PropertyValuesHolder.ofObject("", null, values));
502        } else {
503            PropertyValuesHolder valuesHolder = mValues[0];
504            valuesHolder.setObjectValues(values);
505        }
506        // New property/values/target should cause re-initialization prior to starting
507        mInitialized = false;
508    }
509
510    /**
511     * Sets the values, per property, being animated between. This function is called internally
512     * by the constructors of ValueAnimator that take a list of values. But a ValueAnimator can
513     * be constructed without values and this method can be called to set the values manually
514     * instead.
515     *
516     * @param values The set of values, per property, being animated between.
517     */
518    public void setValues(PropertyValuesHolder... values) {
519        int numValues = values.length;
520        mValues = values;
521        mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues);
522        for (int i = 0; i < numValues; ++i) {
523            PropertyValuesHolder valuesHolder = values[i];
524            mValuesMap.put(valuesHolder.getPropertyName(), valuesHolder);
525        }
526        // New property/values/target should cause re-initialization prior to starting
527        mInitialized = false;
528    }
529
530    /**
531     * Returns the values that this ValueAnimator animates between. These values are stored in
532     * PropertyValuesHolder objects, even if the ValueAnimator was created with a simple list
533     * of value objects instead.
534     *
535     * @return PropertyValuesHolder[] An array of PropertyValuesHolder objects which hold the
536     * values, per property, that define the animation.
537     */
538    public PropertyValuesHolder[] getValues() {
539        return mValues;
540    }
541
542    /**
543     * This function is called immediately before processing the first animation
544     * frame of an animation. If there is a nonzero <code>startDelay</code>, the
545     * function is called after that delay ends.
546     * It takes care of the final initialization steps for the
547     * animation.
548     *
549     *  <p>Overrides of this method should call the superclass method to ensure
550     *  that internal mechanisms for the animation are set up correctly.</p>
551     */
552    @CallSuper
553    void initAnimation() {
554        if (!mInitialized) {
555            int numValues = mValues.length;
556            for (int i = 0; i < numValues; ++i) {
557                mValues[i].init();
558            }
559            mInitialized = true;
560        }
561    }
562
563    /**
564     * Sets the length of the animation. The default duration is 300 milliseconds.
565     *
566     * @param duration The length of the animation, in milliseconds. This value cannot
567     * be negative.
568     * @return ValueAnimator The object called with setDuration(). This return
569     * value makes it easier to compose statements together that construct and then set the
570     * duration, as in <code>ValueAnimator.ofInt(0, 10).setDuration(500).start()</code>.
571     */
572    @Override
573    public ValueAnimator setDuration(long duration) {
574        if (duration < 0) {
575            throw new IllegalArgumentException("Animators cannot have negative duration: " +
576                    duration);
577        }
578        mDuration = duration;
579        return this;
580    }
581
582    private long getScaledDuration() {
583        return (long)(mDuration * sDurationScale);
584    }
585
586    /**
587     * Gets the length of the animation. The default duration is 300 milliseconds.
588     *
589     * @return The length of the animation, in milliseconds.
590     */
591    @Override
592    public long getDuration() {
593        return mDuration;
594    }
595
596    @Override
597    public long getTotalDuration() {
598        if (mRepeatCount == INFINITE) {
599            return DURATION_INFINITE;
600        } else {
601            return mStartDelay + (mDuration * (mRepeatCount + 1));
602        }
603    }
604
605    /**
606     * Sets the position of the animation to the specified point in time. This time should
607     * be between 0 and the total duration of the animation, including any repetition. If
608     * the animation has not yet been started, then it will not advance forward after it is
609     * set to this time; it will simply set the time to this value and perform any appropriate
610     * actions based on that time. If the animation is already running, then setCurrentPlayTime()
611     * will set the current playing time to this value and continue playing from that point.
612     *
613     * @param playTime The time, in milliseconds, to which the animation is advanced or rewound.
614     */
615    public void setCurrentPlayTime(long playTime) {
616        float fraction = mDuration > 0 ? (float) playTime / mDuration : 1;
617        setCurrentFraction(fraction);
618    }
619
620    /**
621     * Sets the position of the animation to the specified fraction. This fraction should
622     * be between 0 and the total fraction of the animation, including any repetition. That is,
623     * a fraction of 0 will position the animation at the beginning, a value of 1 at the end,
624     * and a value of 2 at the end of a reversing animator that repeats once. If
625     * the animation has not yet been started, then it will not advance forward after it is
626     * set to this fraction; it will simply set the fraction to this value and perform any
627     * appropriate actions based on that fraction. If the animation is already running, then
628     * setCurrentFraction() will set the current fraction to this value and continue
629     * playing from that point. {@link Animator.AnimatorListener} events are not called
630     * due to changing the fraction; those events are only processed while the animation
631     * is running.
632     *
633     * @param fraction The fraction to which the animation is advanced or rewound. Values
634     * outside the range of 0 to the maximum fraction for the animator will be clamped to
635     * the correct range.
636     */
637    public void setCurrentFraction(float fraction) {
638        initAnimation();
639        fraction = clampFraction(fraction);
640        mStartTimeCommitted = true; // do not allow start time to be compensated for jank
641        if (isPulsingInternal()) {
642            long seekTime = (long) (getScaledDuration() * fraction);
643            long currentTime = AnimationUtils.currentAnimationTimeMillis();
644            // Only modify the start time when the animation is running. Seek fraction will ensure
645            // non-running animations skip to the correct start time.
646            mStartTime = currentTime - seekTime;
647        } else {
648            // If the animation loop hasn't started, or during start delay, the startTime will be
649            // adjusted once the delay has passed based on seek fraction.
650            mSeekFraction = fraction;
651        }
652        mOverallFraction = fraction;
653        final float currentIterationFraction = getCurrentIterationFraction(fraction, mReversing);
654        animateValue(currentIterationFraction);
655    }
656
657    /**
658     * Calculates current iteration based on the overall fraction. The overall fraction will be
659     * in the range of [0, mRepeatCount + 1]. Both current iteration and fraction in the current
660     * iteration can be derived from it.
661     */
662    private int getCurrentIteration(float fraction) {
663        fraction = clampFraction(fraction);
664        // If the overall fraction is a positive integer, we consider the current iteration to be
665        // complete. In other words, the fraction for the current iteration would be 1, and the
666        // current iteration would be overall fraction - 1.
667        double iteration = Math.floor(fraction);
668        if (fraction == iteration && fraction > 0) {
669            iteration--;
670        }
671        return (int) iteration;
672    }
673
674    /**
675     * Calculates the fraction of the current iteration, taking into account whether the animation
676     * should be played backwards. E.g. When the animation is played backwards in an iteration,
677     * the fraction for that iteration will go from 1f to 0f.
678     */
679    private float getCurrentIterationFraction(float fraction, boolean inReverse) {
680        fraction = clampFraction(fraction);
681        int iteration = getCurrentIteration(fraction);
682        float currentFraction = fraction - iteration;
683        return shouldPlayBackward(iteration, inReverse) ? 1f - currentFraction : currentFraction;
684    }
685
686    /**
687     * Clamps fraction into the correct range: [0, mRepeatCount + 1]. If repeat count is infinite,
688     * no upper bound will be set for the fraction.
689     *
690     * @param fraction fraction to be clamped
691     * @return fraction clamped into the range of [0, mRepeatCount + 1]
692     */
693    private float clampFraction(float fraction) {
694        if (fraction < 0) {
695            fraction = 0;
696        } else if (mRepeatCount != INFINITE) {
697            fraction = Math.min(fraction, mRepeatCount + 1);
698        }
699        return fraction;
700    }
701
702    /**
703     * Calculates the direction of animation playing (i.e. forward or backward), based on 1)
704     * whether the entire animation is being reversed, 2) repeat mode applied to the current
705     * iteration.
706     */
707    private boolean shouldPlayBackward(int iteration, boolean inReverse) {
708        if (iteration > 0 && mRepeatMode == REVERSE &&
709                (iteration < (mRepeatCount + 1) || mRepeatCount == INFINITE)) {
710            // if we were seeked to some other iteration in a reversing animator,
711            // figure out the correct direction to start playing based on the iteration
712            if (inReverse) {
713                return (iteration % 2) == 0;
714            } else {
715                return (iteration % 2) != 0;
716            }
717        } else {
718            return inReverse;
719        }
720    }
721
722    /**
723     * Gets the current position of the animation in time, which is equal to the current
724     * time minus the time that the animation started. An animation that is not yet started will
725     * return a value of zero, unless the animation has has its play time set via
726     * {@link #setCurrentPlayTime(long)} or {@link #setCurrentFraction(float)}, in which case
727     * it will return the time that was set.
728     *
729     * @return The current position in time of the animation.
730     */
731    public long getCurrentPlayTime() {
732        if (!mInitialized || (!mStarted && mSeekFraction < 0)) {
733            return 0;
734        }
735        if (mSeekFraction >= 0) {
736            return (long) (mDuration * mSeekFraction);
737        }
738        float durationScale = sDurationScale == 0 ? 1 : sDurationScale;
739        return (long) ((AnimationUtils.currentAnimationTimeMillis() - mStartTime) / durationScale);
740    }
741
742    /**
743     * The amount of time, in milliseconds, to delay starting the animation after
744     * {@link #start()} is called.
745     *
746     * @return the number of milliseconds to delay running the animation
747     */
748    @Override
749    public long getStartDelay() {
750        return mStartDelay;
751    }
752
753    /**
754     * The amount of time, in milliseconds, to delay starting the animation after
755     * {@link #start()} is called. Note that the start delay should always be non-negative. Any
756     * negative start delay will be clamped to 0 on N and above.
757     *
758     * @param startDelay The amount of the delay, in milliseconds
759     */
760    @Override
761    public void setStartDelay(long startDelay) {
762        // Clamp start delay to non-negative range.
763        if (startDelay < 0) {
764            Log.w(TAG, "Start delay should always be non-negative");
765            startDelay = 0;
766        }
767        mStartDelay = startDelay;
768    }
769
770    /**
771     * The amount of time, in milliseconds, between each frame of the animation. This is a
772     * requested time that the animation will attempt to honor, but the actual delay between
773     * frames may be different, depending on system load and capabilities. This is a static
774     * function because the same delay will be applied to all animations, since they are all
775     * run off of a single timing loop.
776     *
777     * The frame delay may be ignored when the animation system uses an external timing
778     * source, such as the display refresh rate (vsync), to govern animations.
779     *
780     * Note that this method should be called from the same thread that {@link #start()} is
781     * called in order to check the frame delay for that animation. A runtime exception will be
782     * thrown if the calling thread does not have a Looper.
783     *
784     * @return the requested time between frames, in milliseconds
785     */
786    public static long getFrameDelay() {
787        return AnimationHandler.getInstance().getFrameDelay();
788    }
789
790    /**
791     * The amount of time, in milliseconds, between each frame of the animation. This is a
792     * requested time that the animation will attempt to honor, but the actual delay between
793     * frames may be different, depending on system load and capabilities. This is a static
794     * function because the same delay will be applied to all animations, since they are all
795     * run off of a single timing loop.
796     *
797     * The frame delay may be ignored when the animation system uses an external timing
798     * source, such as the display refresh rate (vsync), to govern animations.
799     *
800     * Note that this method should be called from the same thread that {@link #start()} is
801     * called in order to have the new frame delay take effect on that animation. A runtime
802     * exception will be thrown if the calling thread does not have a Looper.
803     *
804     * @param frameDelay the requested time between frames, in milliseconds
805     */
806    public static void setFrameDelay(long frameDelay) {
807        AnimationHandler.getInstance().setFrameDelay(frameDelay);
808    }
809
810    /**
811     * The most recent value calculated by this <code>ValueAnimator</code> when there is just one
812     * property being animated. This value is only sensible while the animation is running. The main
813     * purpose for this read-only property is to retrieve the value from the <code>ValueAnimator</code>
814     * during a call to {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
815     * is called during each animation frame, immediately after the value is calculated.
816     *
817     * @return animatedValue The value most recently calculated by this <code>ValueAnimator</code> for
818     * the single property being animated. If there are several properties being animated
819     * (specified by several PropertyValuesHolder objects in the constructor), this function
820     * returns the animated value for the first of those objects.
821     */
822    public Object getAnimatedValue() {
823        if (mValues != null && mValues.length > 0) {
824            return mValues[0].getAnimatedValue();
825        }
826        // Shouldn't get here; should always have values unless ValueAnimator was set up wrong
827        return null;
828    }
829
830    /**
831     * The most recent value calculated by this <code>ValueAnimator</code> for <code>propertyName</code>.
832     * The main purpose for this read-only property is to retrieve the value from the
833     * <code>ValueAnimator</code> during a call to
834     * {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
835     * is called during each animation frame, immediately after the value is calculated.
836     *
837     * @return animatedValue The value most recently calculated for the named property
838     * by this <code>ValueAnimator</code>.
839     */
840    public Object getAnimatedValue(String propertyName) {
841        PropertyValuesHolder valuesHolder = mValuesMap.get(propertyName);
842        if (valuesHolder != null) {
843            return valuesHolder.getAnimatedValue();
844        } else {
845            // At least avoid crashing if called with bogus propertyName
846            return null;
847        }
848    }
849
850    /**
851     * Sets how many times the animation should be repeated. If the repeat
852     * count is 0, the animation is never repeated. If the repeat count is
853     * greater than 0 or {@link #INFINITE}, the repeat mode will be taken
854     * into account. The repeat count is 0 by default.
855     *
856     * @param value the number of times the animation should be repeated
857     */
858    public void setRepeatCount(int value) {
859        mRepeatCount = value;
860    }
861    /**
862     * Defines how many times the animation should repeat. The default value
863     * is 0.
864     *
865     * @return the number of times the animation should repeat, or {@link #INFINITE}
866     */
867    public int getRepeatCount() {
868        return mRepeatCount;
869    }
870
871    /**
872     * Defines what this animation should do when it reaches the end. This
873     * setting is applied only when the repeat count is either greater than
874     * 0 or {@link #INFINITE}. Defaults to {@link #RESTART}.
875     *
876     * @param value {@link #RESTART} or {@link #REVERSE}
877     */
878    public void setRepeatMode(@RepeatMode int value) {
879        mRepeatMode = value;
880    }
881
882    /**
883     * Defines what this animation should do when it reaches the end.
884     *
885     * @return either one of {@link #REVERSE} or {@link #RESTART}
886     */
887    @RepeatMode
888    public int getRepeatMode() {
889        return mRepeatMode;
890    }
891
892    /**
893     * Adds a listener to the set of listeners that are sent update events through the life of
894     * an animation. This method is called on all listeners for every frame of the animation,
895     * after the values for the animation have been calculated.
896     *
897     * @param listener the listener to be added to the current set of listeners for this animation.
898     */
899    public void addUpdateListener(AnimatorUpdateListener listener) {
900        if (mUpdateListeners == null) {
901            mUpdateListeners = new ArrayList<AnimatorUpdateListener>();
902        }
903        mUpdateListeners.add(listener);
904    }
905
906    /**
907     * Removes all listeners from the set listening to frame updates for this animation.
908     */
909    public void removeAllUpdateListeners() {
910        if (mUpdateListeners == null) {
911            return;
912        }
913        mUpdateListeners.clear();
914        mUpdateListeners = null;
915    }
916
917    /**
918     * Removes a listener from the set listening to frame updates for this animation.
919     *
920     * @param listener the listener to be removed from the current set of update listeners
921     * for this animation.
922     */
923    public void removeUpdateListener(AnimatorUpdateListener listener) {
924        if (mUpdateListeners == null) {
925            return;
926        }
927        mUpdateListeners.remove(listener);
928        if (mUpdateListeners.size() == 0) {
929            mUpdateListeners = null;
930        }
931    }
932
933
934    /**
935     * The time interpolator used in calculating the elapsed fraction of this animation. The
936     * interpolator determines whether the animation runs with linear or non-linear motion,
937     * such as acceleration and deceleration. The default value is
938     * {@link android.view.animation.AccelerateDecelerateInterpolator}
939     *
940     * @param value the interpolator to be used by this animation. A value of <code>null</code>
941     * will result in linear interpolation.
942     */
943    @Override
944    public void setInterpolator(TimeInterpolator value) {
945        if (value != null) {
946            mInterpolator = value;
947        } else {
948            mInterpolator = new LinearInterpolator();
949        }
950    }
951
952    /**
953     * Returns the timing interpolator that this ValueAnimator uses.
954     *
955     * @return The timing interpolator for this ValueAnimator.
956     */
957    @Override
958    public TimeInterpolator getInterpolator() {
959        return mInterpolator;
960    }
961
962    /**
963     * The type evaluator to be used when calculating the animated values of this animation.
964     * The system will automatically assign a float or int evaluator based on the type
965     * of <code>startValue</code> and <code>endValue</code> in the constructor. But if these values
966     * are not one of these primitive types, or if different evaluation is desired (such as is
967     * necessary with int values that represent colors), a custom evaluator needs to be assigned.
968     * For example, when running an animation on color values, the {@link ArgbEvaluator}
969     * should be used to get correct RGB color interpolation.
970     *
971     * <p>If this ValueAnimator has only one set of values being animated between, this evaluator
972     * will be used for that set. If there are several sets of values being animated, which is
973     * the case if PropertyValuesHolder objects were set on the ValueAnimator, then the evaluator
974     * is assigned just to the first PropertyValuesHolder object.</p>
975     *
976     * @param value the evaluator to be used this animation
977     */
978    public void setEvaluator(TypeEvaluator value) {
979        if (value != null && mValues != null && mValues.length > 0) {
980            mValues[0].setEvaluator(value);
981        }
982    }
983
984    private void notifyStartListeners() {
985        if (mListeners != null && !mStartListenersCalled) {
986            ArrayList<AnimatorListener> tmpListeners =
987                    (ArrayList<AnimatorListener>) mListeners.clone();
988            int numListeners = tmpListeners.size();
989            for (int i = 0; i < numListeners; ++i) {
990                tmpListeners.get(i).onAnimationStart(this, mReversing);
991            }
992        }
993        mStartListenersCalled = true;
994    }
995
996    /**
997     * Start the animation playing. This version of start() takes a boolean flag that indicates
998     * whether the animation should play in reverse. The flag is usually false, but may be set
999     * to true if called from the reverse() method.
1000     *
1001     * <p>The animation started by calling this method will be run on the thread that called
1002     * this method. This thread should have a Looper on it (a runtime exception will be thrown if
1003     * this is not the case). Also, if the animation will animate
1004     * properties of objects in the view hierarchy, then the calling thread should be the UI
1005     * thread for that view hierarchy.</p>
1006     *
1007     * @param playBackwards Whether the ValueAnimator should start playing in reverse.
1008     */
1009    private void start(boolean playBackwards) {
1010        if (Looper.myLooper() == null) {
1011            throw new AndroidRuntimeException("Animators may only be run on Looper threads");
1012        }
1013        mReversing = playBackwards;
1014        mSelfPulse = !mSuppressSelfPulseRequested;
1015        // Special case: reversing from seek-to-0 should act as if not seeked at all.
1016        if (playBackwards && mSeekFraction != -1 && mSeekFraction != 0) {
1017            if (mRepeatCount == INFINITE) {
1018                // Calculate the fraction of the current iteration.
1019                float fraction = (float) (mSeekFraction - Math.floor(mSeekFraction));
1020                mSeekFraction = 1 - fraction;
1021            } else {
1022                mSeekFraction = 1 + mRepeatCount - mSeekFraction;
1023            }
1024        }
1025        mStarted = true;
1026        mPaused = false;
1027        mRunning = false;
1028        mAnimationEndRequested = false;
1029        // Resets mLastFrameTime when start() is called, so that if the animation was running,
1030        // calling start() would put the animation in the
1031        // started-but-not-yet-reached-the-first-frame phase.
1032        mLastFrameTime = -1;
1033        mFirstFrameTime = -1;
1034        mStartTime = -1;
1035        addAnimationCallback(0);
1036
1037        if (mStartDelay == 0 || mSeekFraction >= 0 || mReversing) {
1038            // If there's no start delay, init the animation and notify start listeners right away
1039            // to be consistent with the previous behavior. Otherwise, postpone this until the first
1040            // frame after the start delay.
1041            startAnimation();
1042            if (mSeekFraction == -1) {
1043                // No seek, start at play time 0. Note that the reason we are not using fraction 0
1044                // is because for animations with 0 duration, we want to be consistent with pre-N
1045                // behavior: skip to the final value immediately.
1046                setCurrentPlayTime(0);
1047            } else {
1048                setCurrentFraction(mSeekFraction);
1049            }
1050        }
1051    }
1052
1053    void startWithoutPulsing(boolean inReverse) {
1054        mSuppressSelfPulseRequested = true;
1055        if (inReverse) {
1056            reverse();
1057        } else {
1058            start();
1059        }
1060        mSuppressSelfPulseRequested = false;
1061    }
1062
1063    @Override
1064    public void start() {
1065        start(false);
1066    }
1067
1068    @Override
1069    public void cancel() {
1070        if (Looper.myLooper() == null) {
1071            throw new AndroidRuntimeException("Animators may only be run on Looper threads");
1072        }
1073
1074        // If end has already been requested, through a previous end() or cancel() call, no-op
1075        // until animation starts again.
1076        if (mAnimationEndRequested) {
1077            return;
1078        }
1079
1080        // Only cancel if the animation is actually running or has been started and is about
1081        // to run
1082        // Only notify listeners if the animator has actually started
1083        if ((mStarted || mRunning) && mListeners != null) {
1084            if (!mRunning) {
1085                // If it's not yet running, then start listeners weren't called. Call them now.
1086                notifyStartListeners();
1087            }
1088            ArrayList<AnimatorListener> tmpListeners =
1089                    (ArrayList<AnimatorListener>) mListeners.clone();
1090            for (AnimatorListener listener : tmpListeners) {
1091                listener.onAnimationCancel(this);
1092            }
1093        }
1094        endAnimation();
1095
1096    }
1097
1098    @Override
1099    public void end() {
1100        if (Looper.myLooper() == null) {
1101            throw new AndroidRuntimeException("Animators may only be run on Looper threads");
1102        }
1103        if (!mRunning) {
1104            // Special case if the animation has not yet started; get it ready for ending
1105            startAnimation();
1106            mStarted = true;
1107        } else if (!mInitialized) {
1108            initAnimation();
1109        }
1110        animateValue(shouldPlayBackward(mRepeatCount, mReversing) ? 0f : 1f);
1111        endAnimation();
1112    }
1113
1114    @Override
1115    public void resume() {
1116        if (Looper.myLooper() == null) {
1117            throw new AndroidRuntimeException("Animators may only be resumed from the same " +
1118                    "thread that the animator was started on");
1119        }
1120        if (mPaused && !mResumed) {
1121            mResumed = true;
1122            if (mPauseTime > 0) {
1123                addAnimationCallback(0);
1124            }
1125        }
1126        super.resume();
1127    }
1128
1129    @Override
1130    public void pause() {
1131        boolean previouslyPaused = mPaused;
1132        super.pause();
1133        if (!previouslyPaused && mPaused) {
1134            mPauseTime = -1;
1135            mResumed = false;
1136        }
1137    }
1138
1139    @Override
1140    public boolean isRunning() {
1141        return mRunning;
1142    }
1143
1144    @Override
1145    public boolean isStarted() {
1146        return mStarted;
1147    }
1148
1149    /**
1150     * Plays the ValueAnimator in reverse. If the animation is already running,
1151     * it will stop itself and play backwards from the point reached when reverse was called.
1152     * If the animation is not currently running, then it will start from the end and
1153     * play backwards. This behavior is only set for the current animation; future playing
1154     * of the animation will use the default behavior of playing forward.
1155     */
1156    @Override
1157    public void reverse() {
1158        if (isPulsingInternal()) {
1159            long currentTime = AnimationUtils.currentAnimationTimeMillis();
1160            long currentPlayTime = currentTime - mStartTime;
1161            long timeLeft = getScaledDuration() - currentPlayTime;
1162            mStartTime = currentTime - timeLeft;
1163            mStartTimeCommitted = true; // do not allow start time to be compensated for jank
1164            mReversing = !mReversing;
1165        } else if (mStarted) {
1166            mReversing = !mReversing;
1167            end();
1168        } else {
1169            start(true);
1170        }
1171    }
1172
1173    /**
1174     * @hide
1175     */
1176    @Override
1177    public boolean canReverse() {
1178        return true;
1179    }
1180
1181    /**
1182     * Called internally to end an animation by removing it from the animations list. Must be
1183     * called on the UI thread.
1184     */
1185    private void endAnimation() {
1186        if (mAnimationEndRequested) {
1187            return;
1188        }
1189        removeAnimationCallback();
1190
1191        mAnimationEndRequested = true;
1192        mPaused = false;
1193        boolean notify = (mStarted || mRunning) && mListeners != null;
1194        if (notify && !mRunning) {
1195            // If it's not yet running, then start listeners weren't called. Call them now.
1196            notifyStartListeners();
1197        }
1198        mRunning = false;
1199        mStarted = false;
1200        mStartListenersCalled = false;
1201        mLastFrameTime = -1;
1202        mFirstFrameTime = -1;
1203        mStartTime = -1;
1204        if (notify && mListeners != null) {
1205            ArrayList<AnimatorListener> tmpListeners =
1206                    (ArrayList<AnimatorListener>) mListeners.clone();
1207            int numListeners = tmpListeners.size();
1208            for (int i = 0; i < numListeners; ++i) {
1209                tmpListeners.get(i).onAnimationEnd(this, mReversing);
1210            }
1211        }
1212        // mReversing needs to be reset *after* notifying the listeners for the end callbacks.
1213        mReversing = false;
1214        if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
1215            Trace.asyncTraceEnd(Trace.TRACE_TAG_VIEW, getNameForTrace(),
1216                    System.identityHashCode(this));
1217        }
1218    }
1219
1220    /**
1221     * Called internally to start an animation by adding it to the active animations list. Must be
1222     * called on the UI thread.
1223     */
1224    private void startAnimation() {
1225        if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
1226            Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, getNameForTrace(),
1227                    System.identityHashCode(this));
1228        }
1229
1230        mAnimationEndRequested = false;
1231        initAnimation();
1232        mRunning = true;
1233        if (mSeekFraction >= 0) {
1234            mOverallFraction = mSeekFraction;
1235        } else {
1236            mOverallFraction = 0f;
1237        }
1238        if (mListeners != null) {
1239            notifyStartListeners();
1240        }
1241    }
1242
1243    /**
1244     * Internal only: This tracks whether the animation has gotten on the animation loop. Note
1245     * this is different than {@link #isRunning()} in that the latter tracks the time after start()
1246     * is called (or after start delay if any), which may be before the animation loop starts.
1247     */
1248    private boolean isPulsingInternal() {
1249        return mLastFrameTime >= 0;
1250    }
1251
1252    /**
1253     * Returns the name of this animator for debugging purposes.
1254     */
1255    String getNameForTrace() {
1256        return "animator";
1257    }
1258
1259    /**
1260     * Applies an adjustment to the animation to compensate for jank between when
1261     * the animation first ran and when the frame was drawn.
1262     * @hide
1263     */
1264    public void commitAnimationFrame(long frameTime) {
1265        if (!mStartTimeCommitted) {
1266            mStartTimeCommitted = true;
1267            long adjustment = frameTime - mLastFrameTime;
1268            if (adjustment > 0) {
1269                mStartTime += adjustment;
1270                if (DEBUG) {
1271                    Log.d(TAG, "Adjusted start time by " + adjustment + " ms: " + toString());
1272                }
1273            }
1274        }
1275    }
1276
1277    /**
1278     * This internal function processes a single animation frame for a given animation. The
1279     * currentTime parameter is the timing pulse sent by the handler, used to calculate the
1280     * elapsed duration, and therefore
1281     * the elapsed fraction, of the animation. The return value indicates whether the animation
1282     * should be ended (which happens when the elapsed time of the animation exceeds the
1283     * animation's duration, including the repeatCount).
1284     *
1285     * @param currentTime The current time, as tracked by the static timing handler
1286     * @return true if the animation's duration, including any repetitions due to
1287     * <code>repeatCount</code> has been exceeded and the animation should be ended.
1288     */
1289    boolean animateBasedOnTime(long currentTime) {
1290        boolean done = false;
1291        if (mRunning) {
1292            final long scaledDuration = getScaledDuration();
1293            final float fraction = scaledDuration > 0 ?
1294                    (float)(currentTime - mStartTime) / scaledDuration : 1f;
1295            final float lastFraction = mOverallFraction;
1296            final boolean newIteration = (int) fraction > (int) lastFraction;
1297            final boolean lastIterationFinished = (fraction >= mRepeatCount + 1) &&
1298                    (mRepeatCount != INFINITE);
1299            if (scaledDuration == 0) {
1300                // 0 duration animator, ignore the repeat count and skip to the end
1301                done = true;
1302            } else if (newIteration && !lastIterationFinished) {
1303                // Time to repeat
1304                if (mListeners != null) {
1305                    int numListeners = mListeners.size();
1306                    for (int i = 0; i < numListeners; ++i) {
1307                        mListeners.get(i).onAnimationRepeat(this);
1308                    }
1309                }
1310            } else if (lastIterationFinished) {
1311                done = true;
1312            }
1313            mOverallFraction = clampFraction(fraction);
1314            float currentIterationFraction = getCurrentIterationFraction(
1315                    mOverallFraction, mReversing);
1316            animateValue(currentIterationFraction);
1317        }
1318        return done;
1319    }
1320
1321    /**
1322     * Internal use only.
1323     *
1324     * This method does not modify any fields of the animation. It should be called when seeking
1325     * in an AnimatorSet. When the last play time and current play time are of different repeat
1326     * iterations,
1327     * {@link android.view.animation.Animation.AnimationListener#onAnimationRepeat(Animation)}
1328     * will be called.
1329     */
1330    @Override
1331    void animateBasedOnPlayTime(long currentPlayTime, long lastPlayTime, boolean inReverse) {
1332        if (currentPlayTime < 0 || lastPlayTime < 0) {
1333            throw new UnsupportedOperationException("Error: Play time should never be negative.");
1334        }
1335
1336        initAnimation();
1337        // Check whether repeat callback is needed only when repeat count is non-zero
1338        if (mRepeatCount > 0) {
1339            int iteration = (int) (currentPlayTime / mDuration);
1340            int lastIteration = (int) (lastPlayTime / mDuration);
1341
1342            // Clamp iteration to [0, mRepeatCount]
1343            iteration = Math.min(iteration, mRepeatCount);
1344            lastIteration = Math.min(lastIteration, mRepeatCount);
1345
1346            if (iteration != lastIteration) {
1347                if (mListeners != null) {
1348                    int numListeners = mListeners.size();
1349                    for (int i = 0; i < numListeners; ++i) {
1350                        mListeners.get(i).onAnimationRepeat(this);
1351                    }
1352                }
1353            }
1354        }
1355
1356        if (mRepeatCount != INFINITE && currentPlayTime >= (mRepeatCount + 1) * mDuration) {
1357            skipToEndValue(inReverse);
1358        } else {
1359            // Find the current fraction:
1360            float fraction = currentPlayTime / (float) mDuration;
1361            fraction = getCurrentIterationFraction(fraction, inReverse);
1362            animateValue(fraction);
1363        }
1364    }
1365
1366    /**
1367     * Internal use only.
1368     * Skips the animation value to end/start, depending on whether the play direction is forward
1369     * or backward.
1370     *
1371     * @param inReverse whether the end value is based on a reverse direction. If yes, this is
1372     *                  equivalent to skip to start value in a forward playing direction.
1373     */
1374    void skipToEndValue(boolean inReverse) {
1375        initAnimation();
1376        float endFraction = inReverse ? 0f : 1f;
1377        if (mRepeatCount % 2 == 1 && mRepeatMode == REVERSE) {
1378            // This would end on fraction = 0
1379            endFraction = 0f;
1380        }
1381        animateValue(endFraction);
1382    }
1383
1384    @Override
1385    boolean isInitialized() {
1386        return mInitialized;
1387    }
1388
1389    /**
1390     * Processes a frame of the animation, adjusting the start time if needed.
1391     *
1392     * @param frameTime The frame time.
1393     * @return true if the animation has ended.
1394     * @hide
1395     */
1396    public final boolean doAnimationFrame(long frameTime) {
1397        if (mStartTime < 0) {
1398            // First frame. If there is start delay, start delay count down will happen *after* this
1399            // frame.
1400            mStartTime = mReversing ? frameTime : frameTime + (long) (mStartDelay * sDurationScale);
1401        }
1402
1403        // Handle pause/resume
1404        if (mPaused) {
1405            mPauseTime = frameTime;
1406            removeAnimationCallback();
1407            return false;
1408        } else if (mResumed) {
1409            mResumed = false;
1410            if (mPauseTime > 0) {
1411                // Offset by the duration that the animation was paused
1412                mStartTime += (frameTime - mPauseTime);
1413            }
1414        }
1415
1416        if (!mRunning) {
1417            // If not running, that means the animation is in the start delay phase of a forward
1418            // running animation. In the case of reversing, we want to run start delay in the end.
1419            if (mStartTime > frameTime && mSeekFraction == -1) {
1420                // This is when no seek fraction is set during start delay. If developers change the
1421                // seek fraction during the delay, animation will start from the seeked position
1422                // right away.
1423                return false;
1424            } else {
1425                // If mRunning is not set by now, that means non-zero start delay,
1426                // no seeking, not reversing. At this point, start delay has passed.
1427                mRunning = true;
1428                startAnimation();
1429            }
1430        }
1431
1432        if (mLastFrameTime < 0) {
1433            if (mSeekFraction >= 0) {
1434                long seekTime = (long) (getScaledDuration() * mSeekFraction);
1435                mStartTime = frameTime - seekTime;
1436                mSeekFraction = -1;
1437            }
1438            mStartTimeCommitted = false; // allow start time to be compensated for jank
1439        }
1440        mLastFrameTime = frameTime;
1441        // The frame time might be before the start time during the first frame of
1442        // an animation.  The "current time" must always be on or after the start
1443        // time to avoid animating frames at negative time intervals.  In practice, this
1444        // is very rare and only happens when seeking backwards.
1445        final long currentTime = Math.max(frameTime, mStartTime);
1446        boolean finished = animateBasedOnTime(currentTime);
1447
1448        if (finished) {
1449            endAnimation();
1450        }
1451        return finished;
1452    }
1453
1454    @Override
1455    boolean pulseAnimationFrame(long frameTime) {
1456        if (mSelfPulse) {
1457            // Pulse animation frame will *always* be after calling start(). If mSelfPulse isn't
1458            // set to false at this point, that means child animators did not call super's start().
1459            // This can happen when the Animator is just a non-animating wrapper around a real
1460            // functional animation. In this case, we can't really pulse a frame into the animation,
1461            // because the animation cannot necessarily be properly initialized (i.e. no start/end
1462            // values set).
1463            return false;
1464        }
1465        return doAnimationFrame(frameTime);
1466    }
1467
1468    private void addOneShotCommitCallback() {
1469        if (!mSelfPulse) {
1470            return;
1471        }
1472        AnimationHandler handler = AnimationHandler.getInstance();
1473        handler.addOneShotCommitCallback(this);
1474    }
1475
1476    private void removeAnimationCallback() {
1477        if (!mSelfPulse) {
1478            return;
1479        }
1480        AnimationHandler handler = AnimationHandler.getInstance();
1481        handler.removeCallback(this);
1482    }
1483
1484    private void addAnimationCallback(long delay) {
1485        if (!mSelfPulse) {
1486            return;
1487        }
1488        AnimationHandler handler = AnimationHandler.getInstance();
1489        handler.addAnimationFrameCallback(this, delay);
1490    }
1491
1492    /**
1493     * Returns the current animation fraction, which is the elapsed/interpolated fraction used in
1494     * the most recent frame update on the animation.
1495     *
1496     * @return Elapsed/interpolated fraction of the animation.
1497     */
1498    public float getAnimatedFraction() {
1499        return mCurrentFraction;
1500    }
1501
1502    /**
1503     * This method is called with the elapsed fraction of the animation during every
1504     * animation frame. This function turns the elapsed fraction into an interpolated fraction
1505     * and then into an animated value (from the evaluator. The function is called mostly during
1506     * animation updates, but it is also called when the <code>end()</code>
1507     * function is called, to set the final value on the property.
1508     *
1509     * <p>Overrides of this method must call the superclass to perform the calculation
1510     * of the animated value.</p>
1511     *
1512     * @param fraction The elapsed fraction of the animation.
1513     */
1514    @CallSuper
1515    void animateValue(float fraction) {
1516        fraction = mInterpolator.getInterpolation(fraction);
1517        mCurrentFraction = fraction;
1518        int numValues = mValues.length;
1519        for (int i = 0; i < numValues; ++i) {
1520            mValues[i].calculateValue(fraction);
1521        }
1522        if (mUpdateListeners != null) {
1523            int numListeners = mUpdateListeners.size();
1524            for (int i = 0; i < numListeners; ++i) {
1525                mUpdateListeners.get(i).onAnimationUpdate(this);
1526            }
1527        }
1528    }
1529
1530    @Override
1531    public ValueAnimator clone() {
1532        final ValueAnimator anim = (ValueAnimator) super.clone();
1533        if (mUpdateListeners != null) {
1534            anim.mUpdateListeners = new ArrayList<AnimatorUpdateListener>(mUpdateListeners);
1535        }
1536        anim.mSeekFraction = -1;
1537        anim.mReversing = false;
1538        anim.mInitialized = false;
1539        anim.mStarted = false;
1540        anim.mRunning = false;
1541        anim.mPaused = false;
1542        anim.mResumed = false;
1543        anim.mStartListenersCalled = false;
1544        anim.mStartTime = -1;
1545        anim.mStartTimeCommitted = false;
1546        anim.mAnimationEndRequested = false;
1547        anim.mPauseTime = -1;
1548        anim.mLastFrameTime = -1;
1549        anim.mFirstFrameTime = -1;
1550        anim.mOverallFraction = 0;
1551        anim.mCurrentFraction = 0;
1552        anim.mSelfPulse = true;
1553        anim.mSuppressSelfPulseRequested = false;
1554
1555        PropertyValuesHolder[] oldValues = mValues;
1556        if (oldValues != null) {
1557            int numValues = oldValues.length;
1558            anim.mValues = new PropertyValuesHolder[numValues];
1559            anim.mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues);
1560            for (int i = 0; i < numValues; ++i) {
1561                PropertyValuesHolder newValuesHolder = oldValues[i].clone();
1562                anim.mValues[i] = newValuesHolder;
1563                anim.mValuesMap.put(newValuesHolder.getPropertyName(), newValuesHolder);
1564            }
1565        }
1566        return anim;
1567    }
1568
1569    /**
1570     * Implementors of this interface can add themselves as update listeners
1571     * to an <code>ValueAnimator</code> instance to receive callbacks on every animation
1572     * frame, after the current frame's values have been calculated for that
1573     * <code>ValueAnimator</code>.
1574     */
1575    public static interface AnimatorUpdateListener {
1576        /**
1577         * <p>Notifies the occurrence of another frame of the animation.</p>
1578         *
1579         * @param animation The animation which was repeated.
1580         */
1581        void onAnimationUpdate(ValueAnimator animation);
1582
1583    }
1584
1585    /**
1586     * Return the number of animations currently running.
1587     *
1588     * Used by StrictMode internally to annotate violations.
1589     * May be called on arbitrary threads!
1590     *
1591     * @hide
1592     */
1593    public static int getCurrentAnimationsCount() {
1594        return AnimationHandler.getAnimationCount();
1595    }
1596
1597    @Override
1598    public String toString() {
1599        String returnVal = "ValueAnimator@" + Integer.toHexString(hashCode());
1600        if (mValues != null) {
1601            for (int i = 0; i < mValues.length; ++i) {
1602                returnVal += "\n    " + mValues[i].toString();
1603            }
1604        }
1605        return returnVal;
1606    }
1607
1608    /**
1609     * <p>Whether or not the ValueAnimator is allowed to run asynchronously off of
1610     * the UI thread. This is a hint that informs the ValueAnimator that it is
1611     * OK to run the animation off-thread, however ValueAnimator may decide
1612     * that it must run the animation on the UI thread anyway. For example if there
1613     * is an {@link AnimatorUpdateListener} the animation will run on the UI thread,
1614     * regardless of the value of this hint.</p>
1615     *
1616     * <p>Regardless of whether or not the animation runs asynchronously, all
1617     * listener callbacks will be called on the UI thread.</p>
1618     *
1619     * <p>To be able to use this hint the following must be true:</p>
1620     * <ol>
1621     * <li>{@link #getAnimatedFraction()} is not needed (it will return undefined values).</li>
1622     * <li>The animator is immutable while {@link #isStarted()} is true. Requests
1623     *    to change values, duration, delay, etc... may be ignored.</li>
1624     * <li>Lifecycle callback events may be asynchronous. Events such as
1625     *    {@link Animator.AnimatorListener#onAnimationEnd(Animator)} or
1626     *    {@link Animator.AnimatorListener#onAnimationRepeat(Animator)} may end up delayed
1627     *    as they must be posted back to the UI thread, and any actions performed
1628     *    by those callbacks (such as starting new animations) will not happen
1629     *    in the same frame.</li>
1630     * <li>State change requests ({@link #cancel()}, {@link #end()}, {@link #reverse()}, etc...)
1631     *    may be asynchronous. It is guaranteed that all state changes that are
1632     *    performed on the UI thread in the same frame will be applied as a single
1633     *    atomic update, however that frame may be the current frame,
1634     *    the next frame, or some future frame. This will also impact the observed
1635     *    state of the Animator. For example, {@link #isStarted()} may still return true
1636     *    after a call to {@link #end()}. Using the lifecycle callbacks is preferred over
1637     *    queries to {@link #isStarted()}, {@link #isRunning()}, and {@link #isPaused()}
1638     *    for this reason.</li>
1639     * </ol>
1640     * @hide
1641     */
1642    @Override
1643    public void setAllowRunningAsynchronously(boolean mayRunAsync) {
1644        // It is up to subclasses to support this, if they can.
1645    }
1646}
1647