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