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