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