blob: 764e5992fbd967ddb7108f2d8927ee70462feb7c [file] [log] [blame]
Chet Haasea18a86b2010-09-07 13:20:00 -07001/*
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
Tor Norbyec615c6f2015-03-02 10:11:44 -080019import android.annotation.CallSuper;
George Mount7764b922016-01-13 14:51:33 -080020import android.annotation.IntDef;
Teng-Hui Zhu0a815bb2016-08-22 15:48:41 -070021import android.annotation.TestApi;
Mathew Inwooda228c372018-08-01 14:35:45 +010022import android.annotation.UnsupportedAppUsage;
Daniel Santiago Rivera61fe23a2019-02-05 12:41:39 -080023import android.os.Build;
Chet Haasea18a86b2010-09-07 13:20:00 -070024import android.os.Looper;
Romain Guy18772ea2013-04-10 18:31:22 -070025import android.os.Trace;
Chet Haase2970c492010-11-09 13:58:04 -080026import android.util.AndroidRuntimeException;
Jeff Brownc42b28d2015-04-06 19:49:02 -070027import android.util.Log;
Chet Haasea18a86b2010-09-07 13:20:00 -070028import android.view.animation.AccelerateDecelerateInterpolator;
Doris Liu13351992017-01-17 17:10:42 -080029import android.view.animation.Animation;
Chet Haasea18a86b2010-09-07 13:20:00 -070030import android.view.animation.AnimationUtils;
Chet Haase27c1d4d2010-12-16 07:58:28 -080031import android.view.animation.LinearInterpolator;
Chet Haasea18a86b2010-09-07 13:20:00 -070032
George Mount7764b922016-01-13 14:51:33 -080033import java.lang.annotation.Retention;
34import java.lang.annotation.RetentionPolicy;
Chet Haasea18a86b2010-09-07 13:20:00 -070035import java.util.ArrayList;
36import java.util.HashMap;
37
38/**
39 * This class provides a simple timing engine for running animations
40 * which calculate animated values and set them on target objects.
41 *
42 * <p>There is a single timing pulse that all animations use. It runs in a
43 * custom handler to ensure that property changes happen on the UI thread.</p>
44 *
45 * <p>By default, ValueAnimator uses non-linear time interpolation, via the
46 * {@link AccelerateDecelerateInterpolator} class, which accelerates into and decelerates
47 * out of an animation. This behavior can be changed by calling
Chet Haasee0ee2e92010-10-07 09:06:18 -070048 * {@link ValueAnimator#setInterpolator(TimeInterpolator)}.</p>
Joe Fernandez3aef8e1d2011-12-20 10:38:34 -080049 *
Chet Haased4307532014-12-01 06:32:38 -080050 * <p>Animators can be created from either code or resource files. Here is an example
51 * of a ValueAnimator resource file:</p>
52 *
53 * {@sample development/samples/ApiDemos/res/anim/animator.xml ValueAnimatorResources}
54 *
Doris Liu21b93c12016-12-02 15:23:55 -080055 * <p>Starting from API 23, it is also possible to use a combination of {@link PropertyValuesHolder}
56 * and {@link Keyframe} resource tags to create a multi-step animation.
Chet Haased4307532014-12-01 06:32:38 -080057 * Note that you can specify explicit fractional values (from 0 to 1) for
58 * each keyframe to determine when, in the overall duration, the animation should arrive at that
59 * value. Alternatively, you can leave the fractions off and the keyframes will be equally
60 * distributed within the total duration:</p>
61 *
62 * {@sample development/samples/ApiDemos/res/anim/value_animator_pvh_kf.xml
63 * ValueAnimatorKeyframeResources}
64 *
Joe Fernandez3aef8e1d2011-12-20 10:38:34 -080065 * <div class="special reference">
66 * <h3>Developer Guides</h3>
67 * <p>For more information about animating with {@code ValueAnimator}, read the
68 * <a href="{@docRoot}guide/topics/graphics/prop-animation.html#value-animator">Property
69 * Animation</a> developer guide.</p>
70 * </div>
Chet Haasea18a86b2010-09-07 13:20:00 -070071 */
Romain Guy18772ea2013-04-10 18:31:22 -070072@SuppressWarnings("unchecked")
Doris Liu5c71b8c2017-01-31 14:38:21 -080073public class ValueAnimator extends Animator implements AnimationHandler.AnimationFrameCallback {
Jeff Brownc42b28d2015-04-06 19:49:02 -070074 private static final String TAG = "ValueAnimator";
75 private static final boolean DEBUG = false;
Chet Haasea18a86b2010-09-07 13:20:00 -070076
77 /**
78 * Internal constants
79 */
Daniel Santiago Rivera61fe23a2019-02-05 12:41:39 -080080
81 /**
82 * System-wide animation scale.
83 *
84 * <p>To check whether animations are enabled system-wise use {@link #areAnimatorsEnabled()}.
85 */
86 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
Chet Haased21a9fe2012-02-01 14:14:17 -080087 private static float sDurationScale = 1.0f;
Chet Haasea18a86b2010-09-07 13:20:00 -070088
Chet Haasea18a86b2010-09-07 13:20:00 -070089 /**
Chet Haasea18a86b2010-09-07 13:20:00 -070090 * Internal variables
91 * NOTE: This object implements the clone() method, making a deep copy of any referenced
92 * objects. As other non-trivial fields are added to this class, make sure to add logic
93 * to clone() to make deep copies of them.
94 */
95
Jeff Brownc42b28d2015-04-06 19:49:02 -070096 /**
97 * The first time that the animation's animateFrame() method is called. This time is used to
98 * determine elapsed time (and therefore the elapsed fraction) in subsequent calls
99 * to animateFrame().
100 *
101 * Whenever mStartTime is set, you must also update mStartTimeCommitted.
102 */
Doris Liu13351992017-01-17 17:10:42 -0800103 long mStartTime = -1;
Chet Haasea18a86b2010-09-07 13:20:00 -0700104
105 /**
Jeff Brownc42b28d2015-04-06 19:49:02 -0700106 * When true, the start time has been firmly committed as a chosen reference point in
107 * time by which the progress of the animation will be evaluated. When false, the
108 * start time may be updated when the first animation frame is committed so as
109 * to compensate for jank that may have occurred between when the start time was
110 * initialized and when the frame was actually drawn.
111 *
112 * This flag is generally set to false during the first frame of the animation
113 * when the animation playing state transitions from STOPPED to RUNNING or
114 * resumes after having been paused. This flag is set to true when the start time
115 * is firmly committed and should not be further compensated for jank.
116 */
117 boolean mStartTimeCommitted;
118
119 /**
Chet Haasea18a86b2010-09-07 13:20:00 -0700120 * Set when setCurrentPlayTime() is called. If negative, animation is not currently seeked
121 * to a value.
122 */
Chet Haase0d1c27a2014-11-03 18:35:16 +0000123 float mSeekFraction = -1;
Chet Haasea18a86b2010-09-07 13:20:00 -0700124
Chet Haase8aa1ffb2013-08-08 14:00:00 -0700125 /**
126 * Set on the next frame after pause() is called, used to calculate a new startTime
127 * or delayStartTime which allows the animator to continue from the point at which
128 * it was paused. If negative, has not yet been set.
129 */
130 private long mPauseTime;
131
132 /**
133 * Set when an animator is resumed. This triggers logic in the next frame which
134 * actually resumes the animator.
135 */
136 private boolean mResumed = false;
137
Chet Haasea18a86b2010-09-07 13:20:00 -0700138 // The time interpolator to be used if none is set on the animation
Chet Haasee0ee2e92010-10-07 09:06:18 -0700139 private static final TimeInterpolator sDefaultInterpolator =
140 new AccelerateDecelerateInterpolator();
Chet Haasea18a86b2010-09-07 13:20:00 -0700141
Chet Haasea18a86b2010-09-07 13:20:00 -0700142 /**
Chet Haasef4e3bab2014-12-02 17:51:34 -0800143 * Flag to indicate whether this animator is playing in reverse mode, specifically
144 * by being started or interrupted by a call to reverse(). This flag is different than
145 * mPlayingBackwards, which indicates merely whether the current iteration of the
146 * animator is playing in reverse. It is used in corner cases to determine proper end
147 * behavior.
148 */
149 private boolean mReversing;
150
151 /**
Doris Liufbe94ec2015-09-09 14:52:59 -0700152 * Tracks the overall fraction of the animation, ranging from 0 to mRepeatCount + 1
Chet Haasea18a86b2010-09-07 13:20:00 -0700153 */
Doris Liufbe94ec2015-09-09 14:52:59 -0700154 private float mOverallFraction = 0f;
Chet Haasea18a86b2010-09-07 13:20:00 -0700155
156 /**
Chet Haasea00f3862011-02-22 06:34:40 -0800157 * Tracks current elapsed/eased fraction, for querying in getAnimatedFraction().
Doris Liufbe94ec2015-09-09 14:52:59 -0700158 * This is calculated by interpolating the fraction (range: [0, 1]) in the current iteration.
Chet Haasea00f3862011-02-22 06:34:40 -0800159 */
160 private float mCurrentFraction = 0f;
161
162 /**
Doris Liu3618d302015-08-14 11:11:08 -0700163 * Tracks the time (in milliseconds) when the last frame arrived.
Chet Haasea18a86b2010-09-07 13:20:00 -0700164 */
Doris Liu13351992017-01-17 17:10:42 -0800165 private long mLastFrameTime = -1;
166
167 /**
168 * Tracks the time (in milliseconds) when the first frame arrived. Note the frame may arrive
169 * during the start delay.
170 */
171 private long mFirstFrameTime = -1;
Chet Haasea18a86b2010-09-07 13:20:00 -0700172
173 /**
Chet Haaseb8f574a2011-08-03 14:10:06 -0700174 * Additional playing state to indicate whether an animator has been start()'d. There is
175 * some lag between a call to start() and the first animation frame. We should still note
176 * that the animation has been started, even if it's first animation frame has not yet
177 * happened, and reflect that state in isRunning().
178 * Note that delayed animations are different: they are not started until their first
179 * animation frame, which occurs after their delay elapses.
180 */
Chet Haase8b699792011-08-05 15:20:19 -0700181 private boolean mRunning = false;
182
183 /**
184 * Additional playing state to indicate whether an animator has been start()'d, whether or
185 * not there is a nonzero startDelay.
186 */
Chet Haaseb8f574a2011-08-03 14:10:06 -0700187 private boolean mStarted = false;
188
189 /**
Chet Haase8aa1ffb2013-08-08 14:00:00 -0700190 * Tracks whether we've notified listeners of the onAnimationStart() event. This can be
Chet Haase17cf42c2012-04-17 13:18:14 -0700191 * complex to keep track of since we notify listeners at different times depending on
192 * startDelay and whether start() was called before end().
193 */
194 private boolean mStartListenersCalled = false;
195
196 /**
Chet Haasea18a86b2010-09-07 13:20:00 -0700197 * Flag that denotes whether the animation is set up and ready to go. Used to
198 * set up animation that has not yet been started.
199 */
200 boolean mInitialized = false;
201
Doris Liu3dbaae12015-08-27 14:56:30 -0700202 /**
203 * Flag that tracks whether animation has been requested to end.
204 */
205 private boolean mAnimationEndRequested = false;
206
Chet Haasea18a86b2010-09-07 13:20:00 -0700207 //
208 // Backing variables
209 //
210
211 // How long the animation should last in ms
Mathew Inwooda228c372018-08-01 14:35:45 +0100212 @UnsupportedAppUsage
Doris Liufbe94ec2015-09-09 14:52:59 -0700213 private long mDuration = 300;
Chet Haasea18a86b2010-09-07 13:20:00 -0700214
Doris Liufbe94ec2015-09-09 14:52:59 -0700215 // The amount of time in ms to delay starting the animation after start() is called. Note
216 // that this start delay is unscaled. When there is a duration scale set on the animator, the
217 // scaling factor will be applied to this delay.
218 private long mStartDelay = 0;
Chet Haasea18a86b2010-09-07 13:20:00 -0700219
Chet Haasea18a86b2010-09-07 13:20:00 -0700220 // The number of times the animation will repeat. The default is 0, which means the animation
221 // will play only once
222 private int mRepeatCount = 0;
223
224 /**
225 * The type of repetition that will occur when repeatMode is nonzero. RESTART means the
226 * animation will start from the beginning on every new cycle. REVERSE means the animation
227 * will reverse directions on each iteration.
228 */
229 private int mRepeatMode = RESTART;
230
231 /**
Doris Liu13351992017-01-17 17:10:42 -0800232 * Whether or not the animator should register for its own animation callback to receive
233 * animation pulse.
234 */
235 private boolean mSelfPulse = true;
236
237 /**
Doris Liu5c71b8c2017-01-31 14:38:21 -0800238 * Whether or not the animator has been requested to start without pulsing. This flag gets set
239 * in startWithoutPulsing(), and reset in start().
240 */
241 private boolean mSuppressSelfPulseRequested = false;
242
243 /**
Chet Haasea18a86b2010-09-07 13:20:00 -0700244 * The time interpolator to be used. The elapsed fraction of the animation will be passed
245 * through this interpolator to calculate the interpolated fraction, which is then used to
246 * calculate the animated values.
247 */
Chet Haasee0ee2e92010-10-07 09:06:18 -0700248 private TimeInterpolator mInterpolator = sDefaultInterpolator;
Chet Haasea18a86b2010-09-07 13:20:00 -0700249
250 /**
251 * The set of listeners to be sent events through the life of an animation.
252 */
John Reckd3de42c2014-07-15 14:29:33 -0700253 ArrayList<AnimatorUpdateListener> mUpdateListeners = null;
Chet Haasea18a86b2010-09-07 13:20:00 -0700254
255 /**
256 * The property/value sets being animated.
257 */
258 PropertyValuesHolder[] mValues;
259
260 /**
261 * A hashmap of the PropertyValuesHolder objects. This map is used to lookup animated values
262 * by property name during calls to getAnimatedValue(String).
263 */
264 HashMap<String, PropertyValuesHolder> mValuesMap;
265
266 /**
Jorim Jaggic2333b72017-11-13 15:47:46 +0100267 * If set to non-negative value, this will override {@link #sDurationScale}.
268 */
269 private float mDurationScale = -1f;
270
271 /**
Chet Haasea18a86b2010-09-07 13:20:00 -0700272 * Public constants
273 */
274
George Mount7764b922016-01-13 14:51:33 -0800275 /** @hide */
276 @IntDef({RESTART, REVERSE})
277 @Retention(RetentionPolicy.SOURCE)
278 public @interface RepeatMode {}
279
Chet Haasea18a86b2010-09-07 13:20:00 -0700280 /**
281 * When the animation reaches the end and <code>repeatCount</code> is INFINITE
282 * or a positive value, the animation restarts from the beginning.
283 */
284 public static final int RESTART = 1;
285 /**
286 * When the animation reaches the end and <code>repeatCount</code> is INFINITE
287 * or a positive value, the animation reverses direction on every iteration.
288 */
289 public static final int REVERSE = 2;
290 /**
291 * This value used used with the {@link #setRepeatCount(int)} property to repeat
292 * the animation indefinitely.
293 */
294 public static final int INFINITE = -1;
295
Chet Haasec38fa1f2012-02-01 16:37:46 -0800296 /**
297 * @hide
298 */
Artur Satayev5a525852019-10-31 15:15:50 +0000299 @UnsupportedAppUsage
Teng-Hui Zhu0a815bb2016-08-22 15:48:41 -0700300 @TestApi
Chet Haasec38fa1f2012-02-01 16:37:46 -0800301 public static void setDurationScale(float durationScale) {
302 sDurationScale = durationScale;
303 }
304
Chet Haasea18a86b2010-09-07 13:20:00 -0700305 /**
Jeff Brownff7e6ef2012-08-15 02:05:18 -0700306 * @hide
307 */
Artur Satayev5a525852019-10-31 15:15:50 +0000308 @UnsupportedAppUsage
Teng-Hui Zhu0a815bb2016-08-22 15:48:41 -0700309 @TestApi
Jeff Brownff7e6ef2012-08-15 02:05:18 -0700310 public static float getDurationScale() {
311 return sDurationScale;
312 }
313
314 /**
Chet Haase49a513b2016-10-08 09:53:23 -0700315 * Returns whether animators are currently enabled, system-wide. By default, all
316 * animators are enabled. This can change if either the user sets a Developer Option
317 * to set the animator duration scale to 0 or by Battery Savery mode being enabled
318 * (which disables all animations).
319 *
320 * <p>Developers should not typically need to call this method, but should an app wish
321 * to show a different experience when animators are disabled, this return value
322 * can be used as a decider of which experience to offer.
323 *
324 * @return boolean Whether animators are currently enabled. The default value is
325 * <code>true</code>.
326 */
327 public static boolean areAnimatorsEnabled() {
328 return !(sDurationScale == 0);
329 }
330
331 /**
Chet Haasea18a86b2010-09-07 13:20:00 -0700332 * Creates a new ValueAnimator object. This default constructor is primarily for
Chet Haase2794eb32010-10-12 16:29:28 -0700333 * use internally; the factory methods which take parameters are more generally
Chet Haasea18a86b2010-09-07 13:20:00 -0700334 * useful.
335 */
336 public ValueAnimator() {
337 }
338
339 /**
Chet Haase2794eb32010-10-12 16:29:28 -0700340 * Constructs and returns a ValueAnimator that animates between int 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.
Chet Haasea18a86b2010-09-07 13:20:00 -0700346 *
Chet Haase2794eb32010-10-12 16:29:28 -0700347 * @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.
Chet Haasea18a86b2010-09-07 13:20:00 -0700349 */
Chet Haase2794eb32010-10-12 16:29:28 -0700350 public static ValueAnimator ofInt(int... values) {
351 ValueAnimator anim = new ValueAnimator();
352 anim.setIntValues(values);
353 return anim;
354 }
355
356 /**
George Mount1ffb2802013-10-09 16:13:54 -0700357 * Constructs and returns a ValueAnimator that animates between color values. 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 * @param values A set of values that the animation will animate between over time.
365 * @return A ValueAnimator object that is set up to animate between the given values.
366 */
367 public static ValueAnimator ofArgb(int... values) {
368 ValueAnimator anim = new ValueAnimator();
369 anim.setIntValues(values);
370 anim.setEvaluator(ArgbEvaluator.getInstance());
371 return anim;
372 }
373
374 /**
Chet Haase2794eb32010-10-12 16:29:28 -0700375 * Constructs and returns a ValueAnimator that animates between float values. A single
376 * value implies that that value is the one being animated to. However, this is not typically
377 * useful in a ValueAnimator object because there is no way for the object to determine the
378 * starting value for the animation (unlike ObjectAnimator, which can derive that value
379 * from the target object and property being animated). Therefore, there should typically
380 * be two or more values.
381 *
382 * @param values A set of values that the animation will animate between over time.
383 * @return A ValueAnimator object that is set up to animate between the given values.
384 */
385 public static ValueAnimator ofFloat(float... values) {
386 ValueAnimator anim = new ValueAnimator();
387 anim.setFloatValues(values);
388 return anim;
389 }
390
391 /**
Chet Haase2794eb32010-10-12 16:29:28 -0700392 * Constructs and returns a ValueAnimator that animates between the values
393 * specified in the PropertyValuesHolder objects.
394 *
395 * @param values A set of PropertyValuesHolder objects whose values will be animated
396 * between over time.
397 * @return A ValueAnimator object that is set up to animate between the given values.
398 */
399 public static ValueAnimator ofPropertyValuesHolder(PropertyValuesHolder... values) {
400 ValueAnimator anim = new ValueAnimator();
401 anim.setValues(values);
402 return anim;
403 }
404 /**
405 * Constructs and returns a ValueAnimator that animates between Object values. A single
406 * value implies that that value is the one being animated to. However, this is not typically
407 * useful in a ValueAnimator object because there is no way for the object to determine the
408 * starting value for the animation (unlike ObjectAnimator, which can derive that value
409 * from the target object and property being animated). Therefore, there should typically
410 * be two or more values.
411 *
Chet Haasefa21bdf2016-04-21 17:41:54 -0700412 * <p><strong>Note:</strong> The Object values are stored as references to the original
413 * objects, which means that changes to those objects after this method is called will
414 * affect the values on the animator. If the objects will be mutated externally after
415 * this method is called, callers should pass a copy of those objects instead.
416 *
Chet Haase2794eb32010-10-12 16:29:28 -0700417 * <p>Since ValueAnimator does not know how to animate between arbitrary Objects, this
418 * factory method also takes a TypeEvaluator object that the ValueAnimator will use
419 * to perform that interpolation.
420 *
421 * @param evaluator A TypeEvaluator that will be called on each animation frame to
422 * provide the ncessry interpolation between the Object values to derive the animated
423 * value.
424 * @param values A set of values that the animation will animate between over time.
425 * @return A ValueAnimator object that is set up to animate between the given values.
426 */
427 public static ValueAnimator ofObject(TypeEvaluator evaluator, Object... values) {
428 ValueAnimator anim = new ValueAnimator();
429 anim.setObjectValues(values);
430 anim.setEvaluator(evaluator);
431 return anim;
432 }
433
434 /**
435 * Sets int values that will be animated between. A single
436 * value implies that that value is the one being animated to. However, this is not typically
437 * useful in a ValueAnimator object because there is no way for the object to determine the
438 * starting value for the animation (unlike ObjectAnimator, which can derive that value
439 * from the target object and property being animated). Therefore, there should typically
440 * be two or more values.
441 *
442 * <p>If there are already multiple sets of values defined for this ValueAnimator via more
443 * than one PropertyValuesHolder object, this method will set the values for the first
444 * of those objects.</p>
445 *
446 * @param values A set of values that the animation will animate between over time.
447 */
448 public void setIntValues(int... values) {
449 if (values == null || values.length == 0) {
450 return;
Chet Haasea18a86b2010-09-07 13:20:00 -0700451 }
Chet Haase2794eb32010-10-12 16:29:28 -0700452 if (mValues == null || mValues.length == 0) {
Romain Guy18772ea2013-04-10 18:31:22 -0700453 setValues(PropertyValuesHolder.ofInt("", values));
Chet Haase2794eb32010-10-12 16:29:28 -0700454 } else {
455 PropertyValuesHolder valuesHolder = mValues[0];
456 valuesHolder.setIntValues(values);
457 }
458 // New property/values/target should cause re-initialization prior to starting
459 mInitialized = false;
460 }
461
462 /**
463 * Sets float values that will be animated between. A single
464 * value implies that that value is the one being animated to. However, this is not typically
465 * useful in a ValueAnimator object because there is no way for the object to determine the
466 * starting value for the animation (unlike ObjectAnimator, which can derive that value
467 * from the target object and property being animated). Therefore, there should typically
468 * be two or more values.
469 *
470 * <p>If there are already multiple sets of values defined for this ValueAnimator via more
471 * than one PropertyValuesHolder object, this method will set the values for the first
472 * of those objects.</p>
473 *
474 * @param values A set of values that the animation will animate between over time.
475 */
476 public void setFloatValues(float... values) {
477 if (values == null || values.length == 0) {
478 return;
479 }
480 if (mValues == null || mValues.length == 0) {
Romain Guy18772ea2013-04-10 18:31:22 -0700481 setValues(PropertyValuesHolder.ofFloat("", values));
Chet Haase2794eb32010-10-12 16:29:28 -0700482 } else {
483 PropertyValuesHolder valuesHolder = mValues[0];
484 valuesHolder.setFloatValues(values);
485 }
486 // New property/values/target should cause re-initialization prior to starting
487 mInitialized = false;
488 }
489
490 /**
Chet Haase2794eb32010-10-12 16:29:28 -0700491 * Sets the values to animate between for this animation. A single
492 * value implies that that value is the one being animated to. However, this is not typically
493 * useful in a ValueAnimator object because there is no way for the object to determine the
494 * starting value for the animation (unlike ObjectAnimator, which can derive that value
495 * from the target object and property being animated). Therefore, there should typically
496 * be two or more values.
497 *
Chet Haasefa21bdf2016-04-21 17:41:54 -0700498 * <p><strong>Note:</strong> The Object values are stored as references to the original
499 * objects, which means that changes to those objects after this method is called will
500 * affect the values on the animator. If the objects will be mutated externally after
501 * this method is called, callers should pass a copy of those objects instead.
502 *
Chet Haase2794eb32010-10-12 16:29:28 -0700503 * <p>If there are already multiple sets of values defined for this ValueAnimator via more
504 * than one PropertyValuesHolder object, this method will set the values for the first
505 * of those objects.</p>
506 *
507 * <p>There should be a TypeEvaluator set on the ValueAnimator that knows how to interpolate
508 * between these value objects. ValueAnimator only knows how to interpolate between the
509 * primitive types specified in the other setValues() methods.</p>
510 *
511 * @param values The set of values to animate between.
512 */
513 public void setObjectValues(Object... values) {
514 if (values == null || values.length == 0) {
515 return;
516 }
517 if (mValues == null || mValues.length == 0) {
Romain Guy18772ea2013-04-10 18:31:22 -0700518 setValues(PropertyValuesHolder.ofObject("", null, values));
Chet Haase2794eb32010-10-12 16:29:28 -0700519 } else {
520 PropertyValuesHolder valuesHolder = mValues[0];
521 valuesHolder.setObjectValues(values);
522 }
523 // New property/values/target should cause re-initialization prior to starting
524 mInitialized = false;
Chet Haasea18a86b2010-09-07 13:20:00 -0700525 }
526
527 /**
528 * Sets the values, per property, being animated between. This function is called internally
Ken Wakasaf76a50c2012-03-09 19:56:35 +0900529 * by the constructors of ValueAnimator that take a list of values. But a ValueAnimator can
Chet Haasea18a86b2010-09-07 13:20:00 -0700530 * be constructed without values and this method can be called to set the values manually
531 * instead.
532 *
533 * @param values The set of values, per property, being animated between.
534 */
535 public void setValues(PropertyValuesHolder... values) {
536 int numValues = values.length;
537 mValues = values;
538 mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues);
539 for (int i = 0; i < numValues; ++i) {
Romain Guy18772ea2013-04-10 18:31:22 -0700540 PropertyValuesHolder valuesHolder = values[i];
Chet Haasea18a86b2010-09-07 13:20:00 -0700541 mValuesMap.put(valuesHolder.getPropertyName(), valuesHolder);
542 }
Chet Haase0e0590b2010-09-26 11:57:28 -0700543 // New property/values/target should cause re-initialization prior to starting
544 mInitialized = false;
Chet Haasea18a86b2010-09-07 13:20:00 -0700545 }
546
547 /**
548 * Returns the values that this ValueAnimator animates between. These values are stored in
549 * PropertyValuesHolder objects, even if the ValueAnimator was created with a simple list
550 * of value objects instead.
551 *
552 * @return PropertyValuesHolder[] An array of PropertyValuesHolder objects which hold the
553 * values, per property, that define the animation.
554 */
555 public PropertyValuesHolder[] getValues() {
556 return mValues;
557 }
558
559 /**
Chet Haasea18a86b2010-09-07 13:20:00 -0700560 * This function is called immediately before processing the first animation
561 * frame of an animation. If there is a nonzero <code>startDelay</code>, the
562 * function is called after that delay ends.
563 * It takes care of the final initialization steps for the
564 * animation.
565 *
566 * <p>Overrides of this method should call the superclass method to ensure
567 * that internal mechanisms for the animation are set up correctly.</p>
568 */
Tor Norbyec615c6f2015-03-02 10:11:44 -0800569 @CallSuper
Chet Haasea18a86b2010-09-07 13:20:00 -0700570 void initAnimation() {
571 if (!mInitialized) {
572 int numValues = mValues.length;
573 for (int i = 0; i < numValues; ++i) {
574 mValues[i].init();
575 }
Chet Haasea18a86b2010-09-07 13:20:00 -0700576 mInitialized = true;
577 }
578 }
579
Chet Haasea18a86b2010-09-07 13:20:00 -0700580 /**
Chet Haase2794eb32010-10-12 16:29:28 -0700581 * Sets the length of the animation. The default duration is 300 milliseconds.
Chet Haasea18a86b2010-09-07 13:20:00 -0700582 *
Chet Haase27c1d4d2010-12-16 07:58:28 -0800583 * @param duration The length of the animation, in milliseconds. This value cannot
584 * be negative.
Chet Haase2794eb32010-10-12 16:29:28 -0700585 * @return ValueAnimator The object called with setDuration(). This return
586 * value makes it easier to compose statements together that construct and then set the
587 * duration, as in <code>ValueAnimator.ofInt(0, 10).setDuration(500).start()</code>.
Chet Haasea18a86b2010-09-07 13:20:00 -0700588 */
Jeff Brownc42b28d2015-04-06 19:49:02 -0700589 @Override
Chet Haase2794eb32010-10-12 16:29:28 -0700590 public ValueAnimator setDuration(long duration) {
Chet Haase27c1d4d2010-12-16 07:58:28 -0800591 if (duration < 0) {
592 throw new IllegalArgumentException("Animators cannot have negative duration: " +
593 duration);
594 }
Doris Liufbe94ec2015-09-09 14:52:59 -0700595 mDuration = duration;
Chet Haase2794eb32010-10-12 16:29:28 -0700596 return this;
Chet Haasea18a86b2010-09-07 13:20:00 -0700597 }
598
Jorim Jaggic2333b72017-11-13 15:47:46 +0100599 /**
600 * Overrides the global duration scale by a custom value.
601 *
602 * @param durationScale The duration scale to set; or {@code -1f} to use the global duration
603 * scale.
604 * @hide
605 */
606 public void overrideDurationScale(float durationScale) {
607 mDurationScale = durationScale;
608 }
609
610 private float resolveDurationScale() {
611 return mDurationScale >= 0f ? mDurationScale : sDurationScale;
612 }
613
Doris Liufbe94ec2015-09-09 14:52:59 -0700614 private long getScaledDuration() {
Jorim Jaggic2333b72017-11-13 15:47:46 +0100615 return (long)(mDuration * resolveDurationScale());
Jeff Brown7a08fe02014-10-07 15:55:35 -0700616 }
617
Chet Haasea18a86b2010-09-07 13:20:00 -0700618 /**
Chet Haase2794eb32010-10-12 16:29:28 -0700619 * Gets the length of the animation. The default duration is 300 milliseconds.
Chet Haasea18a86b2010-09-07 13:20:00 -0700620 *
621 * @return The length of the animation, in milliseconds.
622 */
Jeff Brownc42b28d2015-04-06 19:49:02 -0700623 @Override
Chet Haasea18a86b2010-09-07 13:20:00 -0700624 public long getDuration() {
Doris Liufbe94ec2015-09-09 14:52:59 -0700625 return mDuration;
Chet Haasea18a86b2010-09-07 13:20:00 -0700626 }
627
Doris Liu13099142015-07-10 17:32:41 -0700628 @Override
629 public long getTotalDuration() {
630 if (mRepeatCount == INFINITE) {
631 return DURATION_INFINITE;
632 } else {
Doris Liufbe94ec2015-09-09 14:52:59 -0700633 return mStartDelay + (mDuration * (mRepeatCount + 1));
Doris Liu13099142015-07-10 17:32:41 -0700634 }
635 }
636
637 /**
Chet Haasea18a86b2010-09-07 13:20:00 -0700638 * Sets the position of the animation to the specified point in time. This time should
639 * be between 0 and the total duration of the animation, including any repetition. If
640 * the animation has not yet been started, then it will not advance forward after it is
641 * set to this time; it will simply set the time to this value and perform any appropriate
642 * actions based on that time. If the animation is already running, then setCurrentPlayTime()
643 * will set the current playing time to this value and continue playing from that point.
644 *
645 * @param playTime The time, in milliseconds, to which the animation is advanced or rewound.
646 */
647 public void setCurrentPlayTime(long playTime) {
Doris Liufbe94ec2015-09-09 14:52:59 -0700648 float fraction = mDuration > 0 ? (float) playTime / mDuration : 1;
Chet Haase0d1c27a2014-11-03 18:35:16 +0000649 setCurrentFraction(fraction);
650 }
651
652 /**
653 * Sets the position of the animation to the specified fraction. This fraction should
654 * be between 0 and the total fraction of the animation, including any repetition. That is,
655 * a fraction of 0 will position the animation at the beginning, a value of 1 at the end,
Chet Haasef4e3bab2014-12-02 17:51:34 -0800656 * and a value of 2 at the end of a reversing animator that repeats once. If
Chet Haase0d1c27a2014-11-03 18:35:16 +0000657 * the animation has not yet been started, then it will not advance forward after it is
658 * set to this fraction; it will simply set the fraction to this value and perform any
659 * appropriate actions based on that fraction. If the animation is already running, then
660 * setCurrentFraction() will set the current fraction to this value and continue
Eino-Ville Talvala5a5afe02014-12-05 11:11:45 -0800661 * playing from that point. {@link Animator.AnimatorListener} events are not called
Chet Haasef4e3bab2014-12-02 17:51:34 -0800662 * due to changing the fraction; those events are only processed while the animation
663 * is running.
Chet Haase0d1c27a2014-11-03 18:35:16 +0000664 *
Chet Haasef4e3bab2014-12-02 17:51:34 -0800665 * @param fraction The fraction to which the animation is advanced or rewound. Values
666 * outside the range of 0 to the maximum fraction for the animator will be clamped to
667 * the correct range.
Chet Haase0d1c27a2014-11-03 18:35:16 +0000668 */
669 public void setCurrentFraction(float fraction) {
Chet Haasea18a86b2010-09-07 13:20:00 -0700670 initAnimation();
Doris Liufbe94ec2015-09-09 14:52:59 -0700671 fraction = clampFraction(fraction);
Jeff Brownc42b28d2015-04-06 19:49:02 -0700672 mStartTimeCommitted = true; // do not allow start time to be compensated for jank
Doris Liu3b466872017-02-03 16:49:20 -0800673 if (isPulsingInternal()) {
674 long seekTime = (long) (getScaledDuration() * fraction);
675 long currentTime = AnimationUtils.currentAnimationTimeMillis();
676 // Only modify the start time when the animation is running. Seek fraction will ensure
677 // non-running animations skip to the correct start time.
678 mStartTime = currentTime - seekTime;
679 } else {
680 // If the animation loop hasn't started, or during start delay, the startTime will be
681 // adjusted once the delay has passed based on seek fraction.
Chet Haase0d1c27a2014-11-03 18:35:16 +0000682 mSeekFraction = fraction;
Chet Haasea18a86b2010-09-07 13:20:00 -0700683 }
Doris Liufbe94ec2015-09-09 14:52:59 -0700684 mOverallFraction = fraction;
Doris Liu13351992017-01-17 17:10:42 -0800685 final float currentIterationFraction = getCurrentIterationFraction(fraction, mReversing);
Doris Liufbe94ec2015-09-09 14:52:59 -0700686 animateValue(currentIterationFraction);
687 }
688
689 /**
690 * Calculates current iteration based on the overall fraction. The overall fraction will be
691 * in the range of [0, mRepeatCount + 1]. Both current iteration and fraction in the current
692 * iteration can be derived from it.
693 */
694 private int getCurrentIteration(float fraction) {
695 fraction = clampFraction(fraction);
696 // If the overall fraction is a positive integer, we consider the current iteration to be
697 // complete. In other words, the fraction for the current iteration would be 1, and the
698 // current iteration would be overall fraction - 1.
699 double iteration = Math.floor(fraction);
700 if (fraction == iteration && fraction > 0) {
701 iteration--;
Chet Haasef4e3bab2014-12-02 17:51:34 -0800702 }
Doris Liufbe94ec2015-09-09 14:52:59 -0700703 return (int) iteration;
704 }
705
706 /**
707 * Calculates the fraction of the current iteration, taking into account whether the animation
708 * should be played backwards. E.g. When the animation is played backwards in an iteration,
709 * the fraction for that iteration will go from 1f to 0f.
710 */
Doris Liu13351992017-01-17 17:10:42 -0800711 private float getCurrentIterationFraction(float fraction, boolean inReverse) {
Doris Liufbe94ec2015-09-09 14:52:59 -0700712 fraction = clampFraction(fraction);
713 int iteration = getCurrentIteration(fraction);
714 float currentFraction = fraction - iteration;
Doris Liu13351992017-01-17 17:10:42 -0800715 return shouldPlayBackward(iteration, inReverse) ? 1f - currentFraction : currentFraction;
Doris Liufbe94ec2015-09-09 14:52:59 -0700716 }
717
718 /**
719 * Clamps fraction into the correct range: [0, mRepeatCount + 1]. If repeat count is infinite,
720 * no upper bound will be set for the fraction.
721 *
722 * @param fraction fraction to be clamped
723 * @return fraction clamped into the range of [0, mRepeatCount + 1]
724 */
725 private float clampFraction(float fraction) {
726 if (fraction < 0) {
727 fraction = 0;
728 } else if (mRepeatCount != INFINITE) {
729 fraction = Math.min(fraction, mRepeatCount + 1);
730 }
731 return fraction;
732 }
733
734 /**
735 * Calculates the direction of animation playing (i.e. forward or backward), based on 1)
736 * whether the entire animation is being reversed, 2) repeat mode applied to the current
737 * iteration.
738 */
Doris Liu13351992017-01-17 17:10:42 -0800739 private boolean shouldPlayBackward(int iteration, boolean inReverse) {
Doris Liufbe94ec2015-09-09 14:52:59 -0700740 if (iteration > 0 && mRepeatMode == REVERSE &&
741 (iteration < (mRepeatCount + 1) || mRepeatCount == INFINITE)) {
742 // if we were seeked to some other iteration in a reversing animator,
743 // figure out the correct direction to start playing based on the iteration
Doris Liu13351992017-01-17 17:10:42 -0800744 if (inReverse) {
Doris Liufbe94ec2015-09-09 14:52:59 -0700745 return (iteration % 2) == 0;
746 } else {
747 return (iteration % 2) != 0;
748 }
749 } else {
Doris Liu13351992017-01-17 17:10:42 -0800750 return inReverse;
Doris Liufbe94ec2015-09-09 14:52:59 -0700751 }
Chet Haasea18a86b2010-09-07 13:20:00 -0700752 }
753
754 /**
755 * Gets the current position of the animation in time, which is equal to the current
756 * time minus the time that the animation started. An animation that is not yet started will
Chet Haase4365e5a2015-10-06 19:32:57 -0700757 * return a value of zero, unless the animation has has its play time set via
758 * {@link #setCurrentPlayTime(long)} or {@link #setCurrentFraction(float)}, in which case
759 * it will return the time that was set.
Chet Haasea18a86b2010-09-07 13:20:00 -0700760 *
761 * @return The current position in time of the animation.
762 */
763 public long getCurrentPlayTime() {
Chet Haase4365e5a2015-10-06 19:32:57 -0700764 if (!mInitialized || (!mStarted && mSeekFraction < 0)) {
Chet Haasea18a86b2010-09-07 13:20:00 -0700765 return 0;
766 }
Chet Haase4365e5a2015-10-06 19:32:57 -0700767 if (mSeekFraction >= 0) {
Doris Liufbe94ec2015-09-09 14:52:59 -0700768 return (long) (mDuration * mSeekFraction);
Chet Haase4365e5a2015-10-06 19:32:57 -0700769 }
Jorim Jaggic2333b72017-11-13 15:47:46 +0100770 float durationScale = resolveDurationScale();
771 if (durationScale == 0f) {
772 durationScale = 1f;
773 }
Doris Liufbe94ec2015-09-09 14:52:59 -0700774 return (long) ((AnimationUtils.currentAnimationTimeMillis() - mStartTime) / durationScale);
Chet Haasea18a86b2010-09-07 13:20:00 -0700775 }
776
777 /**
Chet Haasea18a86b2010-09-07 13:20:00 -0700778 * The amount of time, in milliseconds, to delay starting the animation after
779 * {@link #start()} is called.
780 *
781 * @return the number of milliseconds to delay running the animation
782 */
Jeff Brownc42b28d2015-04-06 19:49:02 -0700783 @Override
Chet Haasea18a86b2010-09-07 13:20:00 -0700784 public long getStartDelay() {
Doris Liufbe94ec2015-09-09 14:52:59 -0700785 return mStartDelay;
Chet Haasea18a86b2010-09-07 13:20:00 -0700786 }
787
788 /**
789 * The amount of time, in milliseconds, to delay starting the animation after
Doris Liu61045c52016-05-24 16:38:19 -0700790 * {@link #start()} is called. Note that the start delay should always be non-negative. Any
791 * negative start delay will be clamped to 0 on N and above.
792 *
Chet Haasea18a86b2010-09-07 13:20:00 -0700793 * @param startDelay The amount of the delay, in milliseconds
794 */
Jeff Brownc42b28d2015-04-06 19:49:02 -0700795 @Override
Chet Haasea18a86b2010-09-07 13:20:00 -0700796 public void setStartDelay(long startDelay) {
Doris Liu61045c52016-05-24 16:38:19 -0700797 // Clamp start delay to non-negative range.
798 if (startDelay < 0) {
799 Log.w(TAG, "Start delay should always be non-negative");
800 startDelay = 0;
801 }
Doris Liufbe94ec2015-09-09 14:52:59 -0700802 mStartDelay = startDelay;
Chet Haasea18a86b2010-09-07 13:20:00 -0700803 }
804
805 /**
806 * The amount of time, in milliseconds, between each frame of the animation. This is a
807 * requested time that the animation will attempt to honor, but the actual delay between
808 * frames may be different, depending on system load and capabilities. This is a static
809 * function because the same delay will be applied to all animations, since they are all
810 * run off of a single timing loop.
811 *
Jeff Brown96e942d2011-11-30 19:55:01 -0800812 * The frame delay may be ignored when the animation system uses an external timing
813 * source, such as the display refresh rate (vsync), to govern animations.
814 *
Doris Liu2b2e2c82015-10-01 11:08:54 -0700815 * Note that this method should be called from the same thread that {@link #start()} is
816 * called in order to check the frame delay for that animation. A runtime exception will be
817 * thrown if the calling thread does not have a Looper.
818 *
Chet Haasea18a86b2010-09-07 13:20:00 -0700819 * @return the requested time between frames, in milliseconds
820 */
821 public static long getFrameDelay() {
Doris Liu3618d302015-08-14 11:11:08 -0700822 return AnimationHandler.getInstance().getFrameDelay();
Chet Haasea18a86b2010-09-07 13:20:00 -0700823 }
824
825 /**
826 * The amount of time, in milliseconds, between each frame of the animation. This is a
827 * requested time that the animation will attempt to honor, but the actual delay between
828 * frames may be different, depending on system load and capabilities. This is a static
829 * function because the same delay will be applied to all animations, since they are all
830 * run off of a single timing loop.
831 *
Jeff Brown96e942d2011-11-30 19:55:01 -0800832 * The frame delay may be ignored when the animation system uses an external timing
833 * source, such as the display refresh rate (vsync), to govern animations.
834 *
Doris Liu2b2e2c82015-10-01 11:08:54 -0700835 * Note that this method should be called from the same thread that {@link #start()} is
836 * called in order to have the new frame delay take effect on that animation. A runtime
837 * exception will be thrown if the calling thread does not have a Looper.
838 *
Chet Haasea18a86b2010-09-07 13:20:00 -0700839 * @param frameDelay the requested time between frames, in milliseconds
840 */
841 public static void setFrameDelay(long frameDelay) {
Doris Liu3618d302015-08-14 11:11:08 -0700842 AnimationHandler.getInstance().setFrameDelay(frameDelay);
Chet Haasea18a86b2010-09-07 13:20:00 -0700843 }
844
845 /**
846 * The most recent value calculated by this <code>ValueAnimator</code> when there is just one
847 * property being animated. This value is only sensible while the animation is running. The main
848 * purpose for this read-only property is to retrieve the value from the <code>ValueAnimator</code>
849 * during a call to {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
850 * is called during each animation frame, immediately after the value is calculated.
851 *
852 * @return animatedValue The value most recently calculated by this <code>ValueAnimator</code> for
853 * the single property being animated. If there are several properties being animated
854 * (specified by several PropertyValuesHolder objects in the constructor), this function
855 * returns the animated value for the first of those objects.
856 */
857 public Object getAnimatedValue() {
858 if (mValues != null && mValues.length > 0) {
859 return mValues[0].getAnimatedValue();
860 }
861 // Shouldn't get here; should always have values unless ValueAnimator was set up wrong
862 return null;
863 }
864
865 /**
866 * The most recent value calculated by this <code>ValueAnimator</code> for <code>propertyName</code>.
867 * The main purpose for this read-only property is to retrieve the value from the
868 * <code>ValueAnimator</code> during a call to
869 * {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
870 * is called during each animation frame, immediately after the value is calculated.
871 *
872 * @return animatedValue The value most recently calculated for the named property
873 * by this <code>ValueAnimator</code>.
874 */
875 public Object getAnimatedValue(String propertyName) {
876 PropertyValuesHolder valuesHolder = mValuesMap.get(propertyName);
877 if (valuesHolder != null) {
878 return valuesHolder.getAnimatedValue();
879 } else {
880 // At least avoid crashing if called with bogus propertyName
881 return null;
882 }
883 }
884
885 /**
886 * Sets how many times the animation should be repeated. If the repeat
887 * count is 0, the animation is never repeated. If the repeat count is
888 * greater than 0 or {@link #INFINITE}, the repeat mode will be taken
889 * into account. The repeat count is 0 by default.
890 *
891 * @param value the number of times the animation should be repeated
892 */
893 public void setRepeatCount(int value) {
894 mRepeatCount = value;
895 }
896 /**
897 * Defines how many times the animation should repeat. The default value
898 * is 0.
899 *
900 * @return the number of times the animation should repeat, or {@link #INFINITE}
901 */
902 public int getRepeatCount() {
903 return mRepeatCount;
904 }
905
906 /**
907 * Defines what this animation should do when it reaches the end. This
908 * setting is applied only when the repeat count is either greater than
909 * 0 or {@link #INFINITE}. Defaults to {@link #RESTART}.
910 *
911 * @param value {@link #RESTART} or {@link #REVERSE}
912 */
George Mount7764b922016-01-13 14:51:33 -0800913 public void setRepeatMode(@RepeatMode int value) {
Chet Haasea18a86b2010-09-07 13:20:00 -0700914 mRepeatMode = value;
915 }
916
917 /**
918 * Defines what this animation should do when it reaches the end.
919 *
920 * @return either one of {@link #REVERSE} or {@link #RESTART}
921 */
George Mount7764b922016-01-13 14:51:33 -0800922 @RepeatMode
Chet Haasea18a86b2010-09-07 13:20:00 -0700923 public int getRepeatMode() {
924 return mRepeatMode;
925 }
926
927 /**
928 * Adds a listener to the set of listeners that are sent update events through the life of
929 * an animation. This method is called on all listeners for every frame of the animation,
930 * after the values for the animation have been calculated.
931 *
932 * @param listener the listener to be added to the current set of listeners for this animation.
933 */
934 public void addUpdateListener(AnimatorUpdateListener listener) {
935 if (mUpdateListeners == null) {
936 mUpdateListeners = new ArrayList<AnimatorUpdateListener>();
937 }
938 mUpdateListeners.add(listener);
939 }
940
941 /**
Jim Miller30604212010-09-22 19:56:23 -0700942 * Removes all listeners from the set listening to frame updates for this animation.
943 */
944 public void removeAllUpdateListeners() {
945 if (mUpdateListeners == null) {
946 return;
947 }
948 mUpdateListeners.clear();
949 mUpdateListeners = null;
950 }
951
952 /**
Chet Haasea18a86b2010-09-07 13:20:00 -0700953 * Removes a listener from the set listening to frame updates for this animation.
954 *
955 * @param listener the listener to be removed from the current set of update listeners
956 * for this animation.
957 */
958 public void removeUpdateListener(AnimatorUpdateListener listener) {
959 if (mUpdateListeners == null) {
960 return;
961 }
962 mUpdateListeners.remove(listener);
963 if (mUpdateListeners.size() == 0) {
964 mUpdateListeners = null;
965 }
966 }
967
968
969 /**
970 * The time interpolator used in calculating the elapsed fraction of this animation. The
971 * interpolator determines whether the animation runs with linear or non-linear motion,
972 * such as acceleration and deceleration. The default value is
973 * {@link android.view.animation.AccelerateDecelerateInterpolator}
974 *
Chet Haase27c1d4d2010-12-16 07:58:28 -0800975 * @param value the interpolator to be used by this animation. A value of <code>null</code>
976 * will result in linear interpolation.
Chet Haasea18a86b2010-09-07 13:20:00 -0700977 */
978 @Override
Chet Haasee0ee2e92010-10-07 09:06:18 -0700979 public void setInterpolator(TimeInterpolator value) {
Chet Haasea18a86b2010-09-07 13:20:00 -0700980 if (value != null) {
981 mInterpolator = value;
Chet Haase27c1d4d2010-12-16 07:58:28 -0800982 } else {
983 mInterpolator = new LinearInterpolator();
Chet Haasea18a86b2010-09-07 13:20:00 -0700984 }
985 }
986
987 /**
988 * Returns the timing interpolator that this ValueAnimator uses.
989 *
990 * @return The timing interpolator for this ValueAnimator.
991 */
Chet Haase430742f2013-04-12 11:18:36 -0700992 @Override
Chet Haasee0ee2e92010-10-07 09:06:18 -0700993 public TimeInterpolator getInterpolator() {
Chet Haasea18a86b2010-09-07 13:20:00 -0700994 return mInterpolator;
995 }
996
997 /**
998 * The type evaluator to be used when calculating the animated values of this animation.
Chet Haaseb2ab04f2011-01-16 11:03:22 -0800999 * The system will automatically assign a float or int evaluator based on the type
Chet Haasea18a86b2010-09-07 13:20:00 -07001000 * of <code>startValue</code> and <code>endValue</code> in the constructor. But if these values
1001 * are not one of these primitive types, or if different evaluation is desired (such as is
1002 * necessary with int values that represent colors), a custom evaluator needs to be assigned.
Chet Haase53ee3312011-01-10 15:56:56 -08001003 * For example, when running an animation on color values, the {@link ArgbEvaluator}
Chet Haasea18a86b2010-09-07 13:20:00 -07001004 * should be used to get correct RGB color interpolation.
1005 *
1006 * <p>If this ValueAnimator has only one set of values being animated between, this evaluator
1007 * will be used for that set. If there are several sets of values being animated, which is
Chet Haasefdd3ad72013-04-24 16:38:20 -07001008 * the case if PropertyValuesHolder objects were set on the ValueAnimator, then the evaluator
Chet Haasea18a86b2010-09-07 13:20:00 -07001009 * is assigned just to the first PropertyValuesHolder object.</p>
1010 *
1011 * @param value the evaluator to be used this animation
1012 */
1013 public void setEvaluator(TypeEvaluator value) {
1014 if (value != null && mValues != null && mValues.length > 0) {
1015 mValues[0].setEvaluator(value);
1016 }
1017 }
1018
Chet Haase17cf42c2012-04-17 13:18:14 -07001019 private void notifyStartListeners() {
1020 if (mListeners != null && !mStartListenersCalled) {
1021 ArrayList<AnimatorListener> tmpListeners =
1022 (ArrayList<AnimatorListener>) mListeners.clone();
1023 int numListeners = tmpListeners.size();
1024 for (int i = 0; i < numListeners; ++i) {
Doris Liu13351992017-01-17 17:10:42 -08001025 tmpListeners.get(i).onAnimationStart(this, mReversing);
Chet Haase17cf42c2012-04-17 13:18:14 -07001026 }
1027 }
1028 mStartListenersCalled = true;
1029 }
1030
Chet Haasea18a86b2010-09-07 13:20:00 -07001031 /**
1032 * Start the animation playing. This version of start() takes a boolean flag that indicates
1033 * whether the animation should play in reverse. The flag is usually false, but may be set
Chet Haase2970c492010-11-09 13:58:04 -08001034 * to true if called from the reverse() method.
1035 *
1036 * <p>The animation started by calling this method will be run on the thread that called
1037 * this method. This thread should have a Looper on it (a runtime exception will be thrown if
1038 * this is not the case). Also, if the animation will animate
1039 * properties of objects in the view hierarchy, then the calling thread should be the UI
1040 * thread for that view hierarchy.</p>
Chet Haasea18a86b2010-09-07 13:20:00 -07001041 *
1042 * @param playBackwards Whether the ValueAnimator should start playing in reverse.
1043 */
Doris Liu5c71b8c2017-01-31 14:38:21 -08001044 private void start(boolean playBackwards) {
Chet Haase2970c492010-11-09 13:58:04 -08001045 if (Looper.myLooper() == null) {
1046 throw new AndroidRuntimeException("Animators may only be run on Looper threads");
Jim Miller30604212010-09-22 19:56:23 -07001047 }
Chet Haasef4e3bab2014-12-02 17:51:34 -08001048 mReversing = playBackwards;
Doris Liu5c71b8c2017-01-31 14:38:21 -08001049 mSelfPulse = !mSuppressSelfPulseRequested;
Doris Liufbe94ec2015-09-09 14:52:59 -07001050 // Special case: reversing from seek-to-0 should act as if not seeked at all.
1051 if (playBackwards && mSeekFraction != -1 && mSeekFraction != 0) {
1052 if (mRepeatCount == INFINITE) {
1053 // Calculate the fraction of the current iteration.
1054 float fraction = (float) (mSeekFraction - Math.floor(mSeekFraction));
1055 mSeekFraction = 1 - fraction;
Chet Haasef4e3bab2014-12-02 17:51:34 -08001056 } else {
Doris Liufbe94ec2015-09-09 14:52:59 -07001057 mSeekFraction = 1 + mRepeatCount - mSeekFraction;
Chet Haasef4e3bab2014-12-02 17:51:34 -08001058 }
1059 }
Chet Haase8b699792011-08-05 15:20:19 -07001060 mStarted = true;
Chet Haase8aa1ffb2013-08-08 14:00:00 -07001061 mPaused = false;
Doris Liu3618d302015-08-14 11:11:08 -07001062 mRunning = false;
Justin Klaassen543a7ed2016-07-22 19:30:03 -07001063 mAnimationEndRequested = false;
Doris Liucaa2ebf2016-06-10 14:46:43 -07001064 // Resets mLastFrameTime when start() is called, so that if the animation was running,
1065 // calling start() would put the animation in the
1066 // started-but-not-yet-reached-the-first-frame phase.
Doris Liu13351992017-01-17 17:10:42 -08001067 mLastFrameTime = -1;
1068 mFirstFrameTime = -1;
Doris Liu6d452092017-02-08 14:47:08 -08001069 mStartTime = -1;
Doris Liu3b466872017-02-03 16:49:20 -08001070 addAnimationCallback(0);
Doris Liuf57bfe22015-10-01 13:26:01 -07001071
Doris Liu13351992017-01-17 17:10:42 -08001072 if (mStartDelay == 0 || mSeekFraction >= 0 || mReversing) {
Doris Liuf57bfe22015-10-01 13:26:01 -07001073 // If there's no start delay, init the animation and notify start listeners right away
Doris Liufbe94ec2015-09-09 14:52:59 -07001074 // to be consistent with the previous behavior. Otherwise, postpone this until the first
1075 // frame after the start delay.
Doris Liuf57bfe22015-10-01 13:26:01 -07001076 startAnimation();
Doris Liub199da72016-02-25 14:23:09 -08001077 if (mSeekFraction == -1) {
1078 // No seek, start at play time 0. Note that the reason we are not using fraction 0
1079 // is because for animations with 0 duration, we want to be consistent with pre-N
1080 // behavior: skip to the final value immediately.
1081 setCurrentPlayTime(0);
1082 } else {
1083 setCurrentFraction(mSeekFraction);
1084 }
Doris Liuf57bfe22015-10-01 13:26:01 -07001085 }
Chet Haasea18a86b2010-09-07 13:20:00 -07001086 }
1087
Doris Liu13351992017-01-17 17:10:42 -08001088 void startWithoutPulsing(boolean inReverse) {
Doris Liu5c71b8c2017-01-31 14:38:21 -08001089 mSuppressSelfPulseRequested = true;
1090 if (inReverse) {
1091 reverse();
1092 } else {
1093 start();
1094 }
1095 mSuppressSelfPulseRequested = false;
Doris Liu13351992017-01-17 17:10:42 -08001096 }
1097
Chet Haasea18a86b2010-09-07 13:20:00 -07001098 @Override
1099 public void start() {
Doris Liu5c71b8c2017-01-31 14:38:21 -08001100 start(false);
Chet Haasea18a86b2010-09-07 13:20:00 -07001101 }
1102
1103 @Override
1104 public void cancel() {
Doris Liu3618d302015-08-14 11:11:08 -07001105 if (Looper.myLooper() == null) {
1106 throw new AndroidRuntimeException("Animators may only be run on Looper threads");
1107 }
Doris Liu3dbaae12015-08-27 14:56:30 -07001108
1109 // If end has already been requested, through a previous end() or cancel() call, no-op
1110 // until animation starts again.
1111 if (mAnimationEndRequested) {
1112 return;
1113 }
1114
Chet Haase2970c492010-11-09 13:58:04 -08001115 // Only cancel if the animation is actually running or has been started and is about
1116 // to run
Doris Liu3618d302015-08-14 11:11:08 -07001117 // Only notify listeners if the animator has actually started
1118 if ((mStarted || mRunning) && mListeners != null) {
1119 if (!mRunning) {
1120 // If it's not yet running, then start listeners weren't called. Call them now.
1121 notifyStartListeners();
Chet Haase7dfacdb2011-07-11 17:01:56 -07001122 }
Doris Liu3618d302015-08-14 11:11:08 -07001123 ArrayList<AnimatorListener> tmpListeners =
1124 (ArrayList<AnimatorListener>) mListeners.clone();
1125 for (AnimatorListener listener : tmpListeners) {
1126 listener.onAnimationCancel(this);
1127 }
Chet Haase2970c492010-11-09 13:58:04 -08001128 }
Doris Liu3618d302015-08-14 11:11:08 -07001129 endAnimation();
1130
Chet Haasea18a86b2010-09-07 13:20:00 -07001131 }
1132
1133 @Override
1134 public void end() {
Doris Liu3618d302015-08-14 11:11:08 -07001135 if (Looper.myLooper() == null) {
1136 throw new AndroidRuntimeException("Animators may only be run on Looper threads");
1137 }
1138 if (!mRunning) {
Chet Haasea18a86b2010-09-07 13:20:00 -07001139 // Special case if the animation has not yet started; get it ready for ending
Doris Liu3618d302015-08-14 11:11:08 -07001140 startAnimation();
Chet Haase17cf42c2012-04-17 13:18:14 -07001141 mStarted = true;
Chet Haaseadd65772011-02-09 16:47:29 -08001142 } else if (!mInitialized) {
1143 initAnimation();
Chet Haasea18a86b2010-09-07 13:20:00 -07001144 }
Doris Liu13351992017-01-17 17:10:42 -08001145 animateValue(shouldPlayBackward(mRepeatCount, mReversing) ? 0f : 1f);
Doris Liu3618d302015-08-14 11:11:08 -07001146 endAnimation();
Chet Haasea18a86b2010-09-07 13:20:00 -07001147 }
1148
1149 @Override
Chet Haase8aa1ffb2013-08-08 14:00:00 -07001150 public void resume() {
George Mounta06b3f12016-03-02 08:06:32 -08001151 if (Looper.myLooper() == null) {
1152 throw new AndroidRuntimeException("Animators may only be resumed from the same " +
1153 "thread that the animator was started on");
1154 }
1155 if (mPaused && !mResumed) {
Chet Haase8aa1ffb2013-08-08 14:00:00 -07001156 mResumed = true;
George Mounta06b3f12016-03-02 08:06:32 -08001157 if (mPauseTime > 0) {
Doris Liu13351992017-01-17 17:10:42 -08001158 addAnimationCallback(0);
George Mounta06b3f12016-03-02 08:06:32 -08001159 }
Chet Haase8aa1ffb2013-08-08 14:00:00 -07001160 }
1161 super.resume();
1162 }
1163
1164 @Override
1165 public void pause() {
1166 boolean previouslyPaused = mPaused;
1167 super.pause();
1168 if (!previouslyPaused && mPaused) {
1169 mPauseTime = -1;
1170 mResumed = false;
1171 }
1172 }
1173
1174 @Override
Chet Haasea18a86b2010-09-07 13:20:00 -07001175 public boolean isRunning() {
Doris Liu3618d302015-08-14 11:11:08 -07001176 return mRunning;
Chet Haase8b699792011-08-05 15:20:19 -07001177 }
1178
1179 @Override
1180 public boolean isStarted() {
1181 return mStarted;
Chet Haasea18a86b2010-09-07 13:20:00 -07001182 }
1183
1184 /**
1185 * Plays the ValueAnimator in reverse. If the animation is already running,
1186 * it will stop itself and play backwards from the point reached when reverse was called.
1187 * If the animation is not currently running, then it will start from the end and
1188 * play backwards. This behavior is only set for the current animation; future playing
1189 * of the animation will use the default behavior of playing forward.
1190 */
ztenghui7bc6a3f2014-07-15 15:12:12 -07001191 @Override
Chet Haasea18a86b2010-09-07 13:20:00 -07001192 public void reverse() {
Doris Liucaa2ebf2016-06-10 14:46:43 -07001193 if (isPulsingInternal()) {
Chet Haasea18a86b2010-09-07 13:20:00 -07001194 long currentTime = AnimationUtils.currentAnimationTimeMillis();
1195 long currentPlayTime = currentTime - mStartTime;
Doris Liufbe94ec2015-09-09 14:52:59 -07001196 long timeLeft = getScaledDuration() - currentPlayTime;
Chet Haasea18a86b2010-09-07 13:20:00 -07001197 mStartTime = currentTime - timeLeft;
Jeff Brownc42b28d2015-04-06 19:49:02 -07001198 mStartTimeCommitted = true; // do not allow start time to be compensated for jank
Chet Haasef4e3bab2014-12-02 17:51:34 -08001199 mReversing = !mReversing;
Chet Haasef43fb2a2013-09-06 07:59:36 -07001200 } else if (mStarted) {
Doris Liucaa2ebf2016-06-10 14:46:43 -07001201 mReversing = !mReversing;
Chet Haasef43fb2a2013-09-06 07:59:36 -07001202 end();
Chet Haasea18a86b2010-09-07 13:20:00 -07001203 } else {
Doris Liu5c71b8c2017-01-31 14:38:21 -08001204 start(true);
Chet Haasea18a86b2010-09-07 13:20:00 -07001205 }
1206 }
1207
1208 /**
ztenghui7bc6a3f2014-07-15 15:12:12 -07001209 * @hide
1210 */
1211 @Override
1212 public boolean canReverse() {
1213 return true;
1214 }
1215
1216 /**
Chet Haasea18a86b2010-09-07 13:20:00 -07001217 * Called internally to end an animation by removing it from the animations list. Must be
1218 * called on the UI thread.
1219 */
Doris Liu3dbaae12015-08-27 14:56:30 -07001220 private void endAnimation() {
1221 if (mAnimationEndRequested) {
1222 return;
1223 }
Doris Liu13351992017-01-17 17:10:42 -08001224 removeAnimationCallback();
Doris Liu3dbaae12015-08-27 14:56:30 -07001225
1226 mAnimationEndRequested = true;
Chet Haase8aa1ffb2013-08-08 14:00:00 -07001227 mPaused = false;
George Mount0eba1df2016-06-13 13:53:37 -07001228 boolean notify = (mStarted || mRunning) && mListeners != null;
1229 if (notify && !mRunning) {
1230 // If it's not yet running, then start listeners weren't called. Call them now.
1231 notifyStartListeners();
1232 }
1233 mRunning = false;
1234 mStarted = false;
1235 mStartListenersCalled = false;
Doris Liu13351992017-01-17 17:10:42 -08001236 mLastFrameTime = -1;
1237 mFirstFrameTime = -1;
Doris Liu6d452092017-02-08 14:47:08 -08001238 mStartTime = -1;
George Mount0eba1df2016-06-13 13:53:37 -07001239 if (notify && mListeners != null) {
Chet Haasea18a86b2010-09-07 13:20:00 -07001240 ArrayList<AnimatorListener> tmpListeners =
1241 (ArrayList<AnimatorListener>) mListeners.clone();
Chet Haase7c608f22010-10-22 17:54:04 -07001242 int numListeners = tmpListeners.size();
1243 for (int i = 0; i < numListeners; ++i) {
Doris Liu13351992017-01-17 17:10:42 -08001244 tmpListeners.get(i).onAnimationEnd(this, mReversing);
Chet Haasea18a86b2010-09-07 13:20:00 -07001245 }
1246 }
Doris Liu6d452092017-02-08 14:47:08 -08001247 // mReversing needs to be reset *after* notifying the listeners for the end callbacks.
Doris Liu13351992017-01-17 17:10:42 -08001248 mReversing = false;
Chet Haase9b80ca82013-06-04 09:37:38 -07001249 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
1250 Trace.asyncTraceEnd(Trace.TRACE_TAG_VIEW, getNameForTrace(),
1251 System.identityHashCode(this));
1252 }
Chet Haasea18a86b2010-09-07 13:20:00 -07001253 }
1254
1255 /**
1256 * Called internally to start an animation by adding it to the active animations list. Must be
1257 * called on the UI thread.
1258 */
Doris Liu3618d302015-08-14 11:11:08 -07001259 private void startAnimation() {
Chet Haase9b80ca82013-06-04 09:37:38 -07001260 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
1261 Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, getNameForTrace(),
1262 System.identityHashCode(this));
1263 }
Doris Liu66d48562015-11-09 14:44:35 -08001264
1265 mAnimationEndRequested = false;
Chet Haasea18a86b2010-09-07 13:20:00 -07001266 initAnimation();
Doris Liu3618d302015-08-14 11:11:08 -07001267 mRunning = true;
Doris Liufbe94ec2015-09-09 14:52:59 -07001268 if (mSeekFraction >= 0) {
1269 mOverallFraction = mSeekFraction;
1270 } else {
1271 mOverallFraction = 0f;
1272 }
Doris Liu3618d302015-08-14 11:11:08 -07001273 if (mListeners != null) {
Chet Haase17cf42c2012-04-17 13:18:14 -07001274 notifyStartListeners();
Chet Haasea18a86b2010-09-07 13:20:00 -07001275 }
1276 }
1277
1278 /**
Doris Liucaa2ebf2016-06-10 14:46:43 -07001279 * Internal only: This tracks whether the animation has gotten on the animation loop. Note
1280 * this is different than {@link #isRunning()} in that the latter tracks the time after start()
1281 * is called (or after start delay if any), which may be before the animation loop starts.
1282 */
1283 private boolean isPulsingInternal() {
Doris Liu13351992017-01-17 17:10:42 -08001284 return mLastFrameTime >= 0;
Doris Liucaa2ebf2016-06-10 14:46:43 -07001285 }
1286
1287 /**
Chet Haasefdd3ad72013-04-24 16:38:20 -07001288 * Returns the name of this animator for debugging purposes.
1289 */
1290 String getNameForTrace() {
1291 return "animator";
1292 }
1293
Chet Haasea18a86b2010-09-07 13:20:00 -07001294 /**
Jeff Brownc42b28d2015-04-06 19:49:02 -07001295 * Applies an adjustment to the animation to compensate for jank between when
1296 * the animation first ran and when the frame was drawn.
Doris Liu3618d302015-08-14 11:11:08 -07001297 * @hide
Jeff Brownc42b28d2015-04-06 19:49:02 -07001298 */
Doris Liu3618d302015-08-14 11:11:08 -07001299 public void commitAnimationFrame(long frameTime) {
Jeff Brownc42b28d2015-04-06 19:49:02 -07001300 if (!mStartTimeCommitted) {
1301 mStartTimeCommitted = true;
Doris Liu3618d302015-08-14 11:11:08 -07001302 long adjustment = frameTime - mLastFrameTime;
1303 if (adjustment > 0) {
Jeff Brownc42b28d2015-04-06 19:49:02 -07001304 mStartTime += adjustment;
1305 if (DEBUG) {
1306 Log.d(TAG, "Adjusted start time by " + adjustment + " ms: " + toString());
1307 }
1308 }
1309 }
1310 }
1311
1312 /**
Chet Haasea18a86b2010-09-07 13:20:00 -07001313 * This internal function processes a single animation frame for a given animation. The
1314 * currentTime parameter is the timing pulse sent by the handler, used to calculate the
1315 * elapsed duration, and therefore
1316 * the elapsed fraction, of the animation. The return value indicates whether the animation
1317 * should be ended (which happens when the elapsed time of the animation exceeds the
1318 * animation's duration, including the repeatCount).
1319 *
1320 * @param currentTime The current time, as tracked by the static timing handler
1321 * @return true if the animation's duration, including any repetitions due to
Doris Liu3618d302015-08-14 11:11:08 -07001322 * <code>repeatCount</code> has been exceeded and the animation should be ended.
Chet Haasea18a86b2010-09-07 13:20:00 -07001323 */
Doris Liu3618d302015-08-14 11:11:08 -07001324 boolean animateBasedOnTime(long currentTime) {
Chet Haasea18a86b2010-09-07 13:20:00 -07001325 boolean done = false;
Doris Liu3618d302015-08-14 11:11:08 -07001326 if (mRunning) {
Doris Liu56b0b572016-04-13 14:13:49 -07001327 final long scaledDuration = getScaledDuration();
1328 final float fraction = scaledDuration > 0 ?
1329 (float)(currentTime - mStartTime) / scaledDuration : 1f;
Doris Liufbe94ec2015-09-09 14:52:59 -07001330 final float lastFraction = mOverallFraction;
1331 final boolean newIteration = (int) fraction > (int) lastFraction;
1332 final boolean lastIterationFinished = (fraction >= mRepeatCount + 1) &&
1333 (mRepeatCount != INFINITE);
Doris Liu56b0b572016-04-13 14:13:49 -07001334 if (scaledDuration == 0) {
1335 // 0 duration animator, ignore the repeat count and skip to the end
1336 done = true;
1337 } else if (newIteration && !lastIterationFinished) {
Doris Liufbe94ec2015-09-09 14:52:59 -07001338 // Time to repeat
1339 if (mListeners != null) {
1340 int numListeners = mListeners.size();
1341 for (int i = 0; i < numListeners; ++i) {
1342 mListeners.get(i).onAnimationRepeat(this);
Chet Haasea18a86b2010-09-07 13:20:00 -07001343 }
Chet Haasea18a86b2010-09-07 13:20:00 -07001344 }
Doris Liufbe94ec2015-09-09 14:52:59 -07001345 } else if (lastIterationFinished) {
1346 done = true;
Chet Haasea18a86b2010-09-07 13:20:00 -07001347 }
Doris Liufbe94ec2015-09-09 14:52:59 -07001348 mOverallFraction = clampFraction(fraction);
Doris Liu13351992017-01-17 17:10:42 -08001349 float currentIterationFraction = getCurrentIterationFraction(
1350 mOverallFraction, mReversing);
Doris Liufbe94ec2015-09-09 14:52:59 -07001351 animateValue(currentIterationFraction);
Chet Haasea18a86b2010-09-07 13:20:00 -07001352 }
Chet Haasea18a86b2010-09-07 13:20:00 -07001353 return done;
1354 }
1355
1356 /**
Doris Liu13351992017-01-17 17:10:42 -08001357 * Internal use only.
1358 *
1359 * This method does not modify any fields of the animation. It should be called when seeking
1360 * in an AnimatorSet. When the last play time and current play time are of different repeat
1361 * iterations,
1362 * {@link android.view.animation.Animation.AnimationListener#onAnimationRepeat(Animation)}
1363 * will be called.
1364 */
1365 @Override
1366 void animateBasedOnPlayTime(long currentPlayTime, long lastPlayTime, boolean inReverse) {
1367 if (currentPlayTime < 0 || lastPlayTime < 0) {
1368 throw new UnsupportedOperationException("Error: Play time should never be negative.");
1369 }
1370
1371 initAnimation();
1372 // Check whether repeat callback is needed only when repeat count is non-zero
1373 if (mRepeatCount > 0) {
1374 int iteration = (int) (currentPlayTime / mDuration);
1375 int lastIteration = (int) (lastPlayTime / mDuration);
1376
1377 // Clamp iteration to [0, mRepeatCount]
1378 iteration = Math.min(iteration, mRepeatCount);
1379 lastIteration = Math.min(lastIteration, mRepeatCount);
1380
1381 if (iteration != lastIteration) {
1382 if (mListeners != null) {
1383 int numListeners = mListeners.size();
1384 for (int i = 0; i < numListeners; ++i) {
1385 mListeners.get(i).onAnimationRepeat(this);
1386 }
1387 }
1388 }
1389 }
1390
1391 if (mRepeatCount != INFINITE && currentPlayTime >= (mRepeatCount + 1) * mDuration) {
1392 skipToEndValue(inReverse);
1393 } else {
1394 // Find the current fraction:
1395 float fraction = currentPlayTime / (float) mDuration;
1396 fraction = getCurrentIterationFraction(fraction, inReverse);
1397 animateValue(fraction);
1398 }
1399 }
1400
1401 /**
1402 * Internal use only.
1403 * Skips the animation value to end/start, depending on whether the play direction is forward
1404 * or backward.
1405 *
1406 * @param inReverse whether the end value is based on a reverse direction. If yes, this is
1407 * equivalent to skip to start value in a forward playing direction.
1408 */
1409 void skipToEndValue(boolean inReverse) {
1410 initAnimation();
1411 float endFraction = inReverse ? 0f : 1f;
1412 if (mRepeatCount % 2 == 1 && mRepeatMode == REVERSE) {
1413 // This would end on fraction = 0
1414 endFraction = 0f;
1415 }
1416 animateValue(endFraction);
1417 }
1418
Doris Liu5c71b8c2017-01-31 14:38:21 -08001419 @Override
1420 boolean isInitialized() {
1421 return mInitialized;
1422 }
1423
Doris Liu13351992017-01-17 17:10:42 -08001424 /**
Jeff Brown20c4f872012-04-26 17:38:21 -07001425 * Processes a frame of the animation, adjusting the start time if needed.
1426 *
1427 * @param frameTime The frame time.
1428 * @return true if the animation has ended.
Doris Liu3618d302015-08-14 11:11:08 -07001429 * @hide
Jeff Brown20c4f872012-04-26 17:38:21 -07001430 */
Doris Liu13351992017-01-17 17:10:42 -08001431 public final boolean doAnimationFrame(long frameTime) {
Doris Liu6d452092017-02-08 14:47:08 -08001432 if (mStartTime < 0) {
1433 // First frame. If there is start delay, start delay count down will happen *after* this
1434 // frame.
Jorim Jaggic2333b72017-11-13 15:47:46 +01001435 mStartTime = mReversing
1436 ? frameTime
1437 : frameTime + (long) (mStartDelay * resolveDurationScale());
Doris Liu13351992017-01-17 17:10:42 -08001438 }
1439
1440 // Handle pause/resume
1441 if (mPaused) {
1442 mPauseTime = frameTime;
1443 removeAnimationCallback();
1444 return false;
1445 } else if (mResumed) {
1446 mResumed = false;
1447 if (mPauseTime > 0) {
1448 // Offset by the duration that the animation was paused
1449 mStartTime += (frameTime - mPauseTime);
1450 }
1451 }
1452
1453 if (!mRunning) {
Doris Liu6d452092017-02-08 14:47:08 -08001454 // If not running, that means the animation is in the start delay phase of a forward
1455 // running animation. In the case of reversing, we want to run start delay in the end.
1456 if (mStartTime > frameTime && mSeekFraction == -1) {
1457 // This is when no seek fraction is set during start delay. If developers change the
1458 // seek fraction during the delay, animation will start from the seeked position
1459 // right away.
Doris Liu13351992017-01-17 17:10:42 -08001460 return false;
1461 } else {
Doris Liu6d452092017-02-08 14:47:08 -08001462 // If mRunning is not set by now, that means non-zero start delay,
1463 // no seeking, not reversing. At this point, start delay has passed.
Doris Liu13351992017-01-17 17:10:42 -08001464 mRunning = true;
Doris Liu6d452092017-02-08 14:47:08 -08001465 startAnimation();
Doris Liu13351992017-01-17 17:10:42 -08001466 }
1467 }
1468
1469 if (mLastFrameTime < 0) {
Doris Liu6d452092017-02-08 14:47:08 -08001470 if (mSeekFraction >= 0) {
Doris Liufbe94ec2015-09-09 14:52:59 -07001471 long seekTime = (long) (getScaledDuration() * mSeekFraction);
Chet Haase0d1c27a2014-11-03 18:35:16 +00001472 mStartTime = frameTime - seekTime;
1473 mSeekFraction = -1;
Jeff Brown20c4f872012-04-26 17:38:21 -07001474 }
Jeff Brownc42b28d2015-04-06 19:49:02 -07001475 mStartTimeCommitted = false; // allow start time to be compensated for jank
Jeff Brown20c4f872012-04-26 17:38:21 -07001476 }
Doris Liuf57bfe22015-10-01 13:26:01 -07001477 mLastFrameTime = frameTime;
Jeff Brown20c4f872012-04-26 17:38:21 -07001478 // The frame time might be before the start time during the first frame of
1479 // an animation. The "current time" must always be on or after the start
1480 // time to avoid animating frames at negative time intervals. In practice, this
1481 // is very rare and only happens when seeking backwards.
1482 final long currentTime = Math.max(frameTime, mStartTime);
Doris Liu3618d302015-08-14 11:11:08 -07001483 boolean finished = animateBasedOnTime(currentTime);
1484
1485 if (finished) {
1486 endAnimation();
1487 }
Doris Liu13351992017-01-17 17:10:42 -08001488 return finished;
1489 }
1490
Doris Liu5c71b8c2017-01-31 14:38:21 -08001491 @Override
1492 boolean pulseAnimationFrame(long frameTime) {
1493 if (mSelfPulse) {
1494 // Pulse animation frame will *always* be after calling start(). If mSelfPulse isn't
1495 // set to false at this point, that means child animators did not call super's start().
1496 // This can happen when the Animator is just a non-animating wrapper around a real
1497 // functional animation. In this case, we can't really pulse a frame into the animation,
1498 // because the animation cannot necessarily be properly initialized (i.e. no start/end
1499 // values set).
1500 return false;
1501 }
1502 return doAnimationFrame(frameTime);
1503 }
1504
Doris Liu13351992017-01-17 17:10:42 -08001505 private void addOneShotCommitCallback() {
1506 if (!mSelfPulse) {
1507 return;
1508 }
Winson Chung4a526c12017-05-16 13:35:43 -07001509 getAnimationHandler().addOneShotCommitCallback(this);
Doris Liu13351992017-01-17 17:10:42 -08001510 }
1511
1512 private void removeAnimationCallback() {
1513 if (!mSelfPulse) {
1514 return;
1515 }
Winson Chung4a526c12017-05-16 13:35:43 -07001516 getAnimationHandler().removeCallback(this);
Doris Liu13351992017-01-17 17:10:42 -08001517 }
1518
1519 private void addAnimationCallback(long delay) {
1520 if (!mSelfPulse) {
1521 return;
1522 }
Winson Chung4a526c12017-05-16 13:35:43 -07001523 getAnimationHandler().addAnimationFrameCallback(this, delay);
Jeff Brown20c4f872012-04-26 17:38:21 -07001524 }
1525
1526 /**
Chet Haasea00f3862011-02-22 06:34:40 -08001527 * Returns the current animation fraction, which is the elapsed/interpolated fraction used in
1528 * the most recent frame update on the animation.
1529 *
1530 * @return Elapsed/interpolated fraction of the animation.
1531 */
1532 public float getAnimatedFraction() {
1533 return mCurrentFraction;
1534 }
1535
1536 /**
Chet Haasea18a86b2010-09-07 13:20:00 -07001537 * This method is called with the elapsed fraction of the animation during every
1538 * animation frame. This function turns the elapsed fraction into an interpolated fraction
1539 * and then into an animated value (from the evaluator. The function is called mostly during
1540 * animation updates, but it is also called when the <code>end()</code>
1541 * function is called, to set the final value on the property.
1542 *
1543 * <p>Overrides of this method must call the superclass to perform the calculation
1544 * of the animated value.</p>
1545 *
1546 * @param fraction The elapsed fraction of the animation.
1547 */
Tor Norbyec615c6f2015-03-02 10:11:44 -08001548 @CallSuper
Mathew Inwooda228c372018-08-01 14:35:45 +01001549 @UnsupportedAppUsage
Chet Haasea18a86b2010-09-07 13:20:00 -07001550 void animateValue(float fraction) {
1551 fraction = mInterpolator.getInterpolation(fraction);
Chet Haasea00f3862011-02-22 06:34:40 -08001552 mCurrentFraction = fraction;
Chet Haasea18a86b2010-09-07 13:20:00 -07001553 int numValues = mValues.length;
1554 for (int i = 0; i < numValues; ++i) {
1555 mValues[i].calculateValue(fraction);
1556 }
1557 if (mUpdateListeners != null) {
1558 int numListeners = mUpdateListeners.size();
1559 for (int i = 0; i < numListeners; ++i) {
1560 mUpdateListeners.get(i).onAnimationUpdate(this);
1561 }
1562 }
1563 }
1564
1565 @Override
1566 public ValueAnimator clone() {
1567 final ValueAnimator anim = (ValueAnimator) super.clone();
1568 if (mUpdateListeners != null) {
Yigit Boyard422dc32014-09-25 12:23:35 -07001569 anim.mUpdateListeners = new ArrayList<AnimatorUpdateListener>(mUpdateListeners);
Chet Haasea18a86b2010-09-07 13:20:00 -07001570 }
Chet Haase0d1c27a2014-11-03 18:35:16 +00001571 anim.mSeekFraction = -1;
Chet Haasef4e3bab2014-12-02 17:51:34 -08001572 anim.mReversing = false;
Chet Haasea18a86b2010-09-07 13:20:00 -07001573 anim.mInitialized = false;
ztenghui26e9a192015-04-10 13:14:17 -07001574 anim.mStarted = false;
1575 anim.mRunning = false;
1576 anim.mPaused = false;
1577 anim.mResumed = false;
1578 anim.mStartListenersCalled = false;
Doris Liu13351992017-01-17 17:10:42 -08001579 anim.mStartTime = -1;
ztenghuie1b5c2b2015-04-21 14:17:00 -07001580 anim.mStartTimeCommitted = false;
Doris Liu3dbaae12015-08-27 14:56:30 -07001581 anim.mAnimationEndRequested = false;
Doris Liu13351992017-01-17 17:10:42 -08001582 anim.mPauseTime = -1;
1583 anim.mLastFrameTime = -1;
1584 anim.mFirstFrameTime = -1;
Doris Liufbe94ec2015-09-09 14:52:59 -07001585 anim.mOverallFraction = 0;
ztenghuie1b5c2b2015-04-21 14:17:00 -07001586 anim.mCurrentFraction = 0;
Doris Liu5c71b8c2017-01-31 14:38:21 -08001587 anim.mSelfPulse = true;
1588 anim.mSuppressSelfPulseRequested = false;
ztenghui26e9a192015-04-10 13:14:17 -07001589
Chet Haasea18a86b2010-09-07 13:20:00 -07001590 PropertyValuesHolder[] oldValues = mValues;
1591 if (oldValues != null) {
1592 int numValues = oldValues.length;
1593 anim.mValues = new PropertyValuesHolder[numValues];
Chet Haasea18a86b2010-09-07 13:20:00 -07001594 anim.mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues);
1595 for (int i = 0; i < numValues; ++i) {
Chet Haased4dd7022011-04-04 15:25:09 -07001596 PropertyValuesHolder newValuesHolder = oldValues[i].clone();
1597 anim.mValues[i] = newValuesHolder;
1598 anim.mValuesMap.put(newValuesHolder.getPropertyName(), newValuesHolder);
Chet Haasea18a86b2010-09-07 13:20:00 -07001599 }
1600 }
1601 return anim;
1602 }
1603
1604 /**
1605 * Implementors of this interface can add themselves as update listeners
1606 * to an <code>ValueAnimator</code> instance to receive callbacks on every animation
1607 * frame, after the current frame's values have been calculated for that
1608 * <code>ValueAnimator</code>.
1609 */
1610 public static interface AnimatorUpdateListener {
1611 /**
1612 * <p>Notifies the occurrence of another frame of the animation.</p>
1613 *
1614 * @param animation The animation which was repeated.
1615 */
1616 void onAnimationUpdate(ValueAnimator animation);
1617
1618 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07001619
1620 /**
1621 * Return the number of animations currently running.
1622 *
Jeff Brown9c38dbe2011-12-02 16:22:46 -08001623 * Used by StrictMode internally to annotate violations.
1624 * May be called on arbitrary threads!
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07001625 *
1626 * @hide
1627 */
1628 public static int getCurrentAnimationsCount() {
Doris Liu3618d302015-08-14 11:11:08 -07001629 return AnimationHandler.getAnimationCount();
Patrick Dubroy8901ffa2011-01-16 17:13:55 -08001630 }
Chet Haasee9140a72011-02-16 16:23:29 -08001631
1632 @Override
1633 public String toString() {
1634 String returnVal = "ValueAnimator@" + Integer.toHexString(hashCode());
1635 if (mValues != null) {
1636 for (int i = 0; i < mValues.length; ++i) {
1637 returnVal += "\n " + mValues[i].toString();
1638 }
1639 }
1640 return returnVal;
1641 }
John Reckd3de42c2014-07-15 14:29:33 -07001642
1643 /**
1644 * <p>Whether or not the ValueAnimator is allowed to run asynchronously off of
1645 * the UI thread. This is a hint that informs the ValueAnimator that it is
1646 * OK to run the animation off-thread, however ValueAnimator may decide
1647 * that it must run the animation on the UI thread anyway. For example if there
1648 * is an {@link AnimatorUpdateListener} the animation will run on the UI thread,
1649 * regardless of the value of this hint.</p>
1650 *
1651 * <p>Regardless of whether or not the animation runs asynchronously, all
1652 * listener callbacks will be called on the UI thread.</p>
1653 *
1654 * <p>To be able to use this hint the following must be true:</p>
1655 * <ol>
1656 * <li>{@link #getAnimatedFraction()} is not needed (it will return undefined values).</li>
1657 * <li>The animator is immutable while {@link #isStarted()} is true. Requests
1658 * to change values, duration, delay, etc... may be ignored.</li>
1659 * <li>Lifecycle callback events may be asynchronous. Events such as
1660 * {@link Animator.AnimatorListener#onAnimationEnd(Animator)} or
1661 * {@link Animator.AnimatorListener#onAnimationRepeat(Animator)} may end up delayed
1662 * as they must be posted back to the UI thread, and any actions performed
1663 * by those callbacks (such as starting new animations) will not happen
1664 * in the same frame.</li>
1665 * <li>State change requests ({@link #cancel()}, {@link #end()}, {@link #reverse()}, etc...)
1666 * may be asynchronous. It is guaranteed that all state changes that are
1667 * performed on the UI thread in the same frame will be applied as a single
1668 * atomic update, however that frame may be the current frame,
1669 * the next frame, or some future frame. This will also impact the observed
1670 * state of the Animator. For example, {@link #isStarted()} may still return true
1671 * after a call to {@link #end()}. Using the lifecycle callbacks is preferred over
1672 * queries to {@link #isStarted()}, {@link #isRunning()}, and {@link #isPaused()}
1673 * for this reason.</li>
1674 * </ol>
1675 * @hide
1676 */
John Reckc01bd112014-07-18 16:22:09 -07001677 @Override
John Reckd3de42c2014-07-15 14:29:33 -07001678 public void setAllowRunningAsynchronously(boolean mayRunAsync) {
1679 // It is up to subclasses to support this, if they can.
1680 }
Winson Chung4a526c12017-05-16 13:35:43 -07001681
1682 /**
1683 * @return The {@link AnimationHandler} that will be used to schedule updates for this animator.
1684 * @hide
1685 */
1686 public AnimationHandler getAnimationHandler() {
1687 return AnimationHandler.getInstance();
1688 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07001689}