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