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