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