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