ValueAnimator.java revision add6577a0196258e5a48c5deefcdb12e05c935b3
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 primitive types handled by this implementation 147 private static final TypeEvaluator sIntEvaluator = new IntEvaluator(); 148 private static final TypeEvaluator sFloatEvaluator = new FloatEvaluator(); 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. This value cannot 482 * be negative. 483 * @return ValueAnimator The object called with setDuration(). This return 484 * value makes it easier to compose statements together that construct and then set the 485 * duration, as in <code>ValueAnimator.ofInt(0, 10).setDuration(500).start()</code>. 486 */ 487 public ValueAnimator setDuration(long duration) { 488 if (duration < 0) { 489 throw new IllegalArgumentException("Animators cannot have negative duration: " + 490 duration); 491 } 492 mDuration = duration; 493 return this; 494 } 495 496 /** 497 * Gets the length of the animation. The default duration is 300 milliseconds. 498 * 499 * @return The length of the animation, in milliseconds. 500 */ 501 public long getDuration() { 502 return mDuration; 503 } 504 505 /** 506 * Sets the position of the animation to the specified point in time. This time should 507 * be between 0 and the total duration of the animation, including any repetition. If 508 * the animation has not yet been started, then it will not advance forward after it is 509 * set to this time; it will simply set the time to this value and perform any appropriate 510 * actions based on that time. If the animation is already running, then setCurrentPlayTime() 511 * will set the current playing time to this value and continue playing from that point. 512 * 513 * @param playTime The time, in milliseconds, to which the animation is advanced or rewound. 514 */ 515 public void setCurrentPlayTime(long playTime) { 516 initAnimation(); 517 long currentTime = AnimationUtils.currentAnimationTimeMillis(); 518 if (mPlayingState != RUNNING) { 519 mSeekTime = playTime; 520 mPlayingState = SEEKED; 521 } 522 mStartTime = currentTime - playTime; 523 animationFrame(currentTime); 524 } 525 526 /** 527 * Gets the current position of the animation in time, which is equal to the current 528 * time minus the time that the animation started. An animation that is not yet started will 529 * return a value of zero. 530 * 531 * @return The current position in time of the animation. 532 */ 533 public long getCurrentPlayTime() { 534 if (!mInitialized || mPlayingState == STOPPED) { 535 return 0; 536 } 537 return AnimationUtils.currentAnimationTimeMillis() - mStartTime; 538 } 539 540 /** 541 * This custom, static handler handles the timing pulse that is shared by 542 * all active animations. This approach ensures that the setting of animation 543 * values will happen on the UI thread and that all animations will share 544 * the same times for calculating their values, which makes synchronizing 545 * animations possible. 546 * 547 */ 548 private static class AnimationHandler extends Handler { 549 /** 550 * There are only two messages that we care about: ANIMATION_START and 551 * ANIMATION_FRAME. The START message is sent when an animation's start() 552 * method is called. It cannot start synchronously when start() is called 553 * because the call may be on the wrong thread, and it would also not be 554 * synchronized with other animations because it would not start on a common 555 * timing pulse. So each animation sends a START message to the handler, which 556 * causes the handler to place the animation on the active animations queue and 557 * start processing frames for that animation. 558 * The FRAME message is the one that is sent over and over while there are any 559 * active animations to process. 560 */ 561 @Override 562 public void handleMessage(Message msg) { 563 boolean callAgain = true; 564 ArrayList<ValueAnimator> animations = sAnimations.get(); 565 ArrayList<ValueAnimator> delayedAnims = sDelayedAnims.get(); 566 switch (msg.what) { 567 // TODO: should we avoid sending frame message when starting if we 568 // were already running? 569 case ANIMATION_START: 570 ArrayList<ValueAnimator> pendingAnimations = sPendingAnimations.get(); 571 if (animations.size() > 0 || delayedAnims.size() > 0) { 572 callAgain = false; 573 } 574 // pendingAnims holds any animations that have requested to be started 575 // We're going to clear sPendingAnimations, but starting animation may 576 // cause more to be added to the pending list (for example, if one animation 577 // starting triggers another starting). So we loop until sPendingAnimations 578 // is empty. 579 while (pendingAnimations.size() > 0) { 580 ArrayList<ValueAnimator> pendingCopy = 581 (ArrayList<ValueAnimator>) pendingAnimations.clone(); 582 pendingAnimations.clear(); 583 int count = pendingCopy.size(); 584 for (int i = 0; i < count; ++i) { 585 ValueAnimator anim = pendingCopy.get(i); 586 // If the animation has a startDelay, place it on the delayed list 587 if (anim.mStartDelay == 0) { 588 anim.startAnimation(); 589 } else { 590 delayedAnims.add(anim); 591 } 592 } 593 } 594 // fall through to process first frame of new animations 595 case ANIMATION_FRAME: 596 // currentTime holds the common time for all animations processed 597 // during this frame 598 long currentTime = AnimationUtils.currentAnimationTimeMillis(); 599 ArrayList<ValueAnimator> readyAnims = sReadyAnims.get(); 600 ArrayList<ValueAnimator> endingAnims = sEndingAnims.get(); 601 602 // First, process animations currently sitting on the delayed queue, adding 603 // them to the active animations if they are ready 604 int numDelayedAnims = delayedAnims.size(); 605 for (int i = 0; i < numDelayedAnims; ++i) { 606 ValueAnimator anim = delayedAnims.get(i); 607 if (anim.delayedAnimationFrame(currentTime)) { 608 readyAnims.add(anim); 609 } 610 } 611 int numReadyAnims = readyAnims.size(); 612 if (numReadyAnims > 0) { 613 for (int i = 0; i < numReadyAnims; ++i) { 614 ValueAnimator anim = readyAnims.get(i); 615 anim.startAnimation(); 616 delayedAnims.remove(anim); 617 } 618 readyAnims.clear(); 619 } 620 621 // Now process all active animations. The return value from animationFrame() 622 // tells the handler whether it should now be ended 623 int numAnims = animations.size(); 624 int i = 0; 625 while (i < numAnims) { 626 ValueAnimator anim = animations.get(i); 627 if (anim.animationFrame(currentTime)) { 628 endingAnims.add(anim); 629 } 630 if (animations.size() == numAnims) { 631 ++i; 632 } else { 633 // An animation might be canceled or ended by client code 634 // during the animation frame. Check to see if this happened by 635 // seeing whether the current index is the same as it was before 636 // calling animationFrame(). Another approach would be to copy 637 // animations to a temporary list and process that list instead, 638 // but that entails garbage and processing overhead that would 639 // be nice to avoid. 640 --numAnims; 641 endingAnims.remove(anim); 642 } 643 } 644 if (endingAnims.size() > 0) { 645 for (i = 0; i < endingAnims.size(); ++i) { 646 endingAnims.get(i).endAnimation(); 647 } 648 endingAnims.clear(); 649 } 650 651 // If there are still active or delayed animations, call the handler again 652 // after the frameDelay 653 if (callAgain && (!animations.isEmpty() || !delayedAnims.isEmpty())) { 654 sendEmptyMessageDelayed(ANIMATION_FRAME, Math.max(0, sFrameDelay - 655 (AnimationUtils.currentAnimationTimeMillis() - currentTime))); 656 } 657 break; 658 } 659 } 660 } 661 662 /** 663 * The amount of time, in milliseconds, to delay starting the animation after 664 * {@link #start()} is called. 665 * 666 * @return the number of milliseconds to delay running the animation 667 */ 668 public long getStartDelay() { 669 return mStartDelay; 670 } 671 672 /** 673 * The amount of time, in milliseconds, to delay starting the animation after 674 * {@link #start()} is called. 675 676 * @param startDelay The amount of the delay, in milliseconds 677 */ 678 public void setStartDelay(long startDelay) { 679 this.mStartDelay = startDelay; 680 } 681 682 /** 683 * The amount of time, in milliseconds, between each frame of the animation. This is a 684 * requested time that the animation will attempt to honor, but the actual delay between 685 * frames may be different, depending on system load and capabilities. This is a static 686 * function because the same delay will be applied to all animations, since they are all 687 * run off of a single timing loop. 688 * 689 * @return the requested time between frames, in milliseconds 690 */ 691 public static long getFrameDelay() { 692 return sFrameDelay; 693 } 694 695 /** 696 * The amount of time, in milliseconds, between each frame of the animation. This is a 697 * requested time that the animation will attempt to honor, but the actual delay between 698 * frames may be different, depending on system load and capabilities. This is a static 699 * function because the same delay will be applied to all animations, since they are all 700 * run off of a single timing loop. 701 * 702 * @param frameDelay the requested time between frames, in milliseconds 703 */ 704 public static void setFrameDelay(long frameDelay) { 705 sFrameDelay = frameDelay; 706 } 707 708 /** 709 * The most recent value calculated by this <code>ValueAnimator</code> when there is just one 710 * property being animated. This value is only sensible while the animation is running. The main 711 * purpose for this read-only property is to retrieve the value from the <code>ValueAnimator</code> 712 * during a call to {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which 713 * is called during each animation frame, immediately after the value is calculated. 714 * 715 * @return animatedValue The value most recently calculated by this <code>ValueAnimator</code> for 716 * the single property being animated. If there are several properties being animated 717 * (specified by several PropertyValuesHolder objects in the constructor), this function 718 * returns the animated value for the first of those objects. 719 */ 720 public Object getAnimatedValue() { 721 if (mValues != null && mValues.length > 0) { 722 return mValues[0].getAnimatedValue(); 723 } 724 // Shouldn't get here; should always have values unless ValueAnimator was set up wrong 725 return null; 726 } 727 728 /** 729 * The most recent value calculated by this <code>ValueAnimator</code> for <code>propertyName</code>. 730 * The main purpose for this read-only property is to retrieve the value from the 731 * <code>ValueAnimator</code> during a call to 732 * {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which 733 * is called during each animation frame, immediately after the value is calculated. 734 * 735 * @return animatedValue The value most recently calculated for the named property 736 * by this <code>ValueAnimator</code>. 737 */ 738 public Object getAnimatedValue(String propertyName) { 739 PropertyValuesHolder valuesHolder = mValuesMap.get(propertyName); 740 if (valuesHolder != null) { 741 return valuesHolder.getAnimatedValue(); 742 } else { 743 // At least avoid crashing if called with bogus propertyName 744 return null; 745 } 746 } 747 748 /** 749 * Sets how many times the animation should be repeated. If the repeat 750 * count is 0, the animation is never repeated. If the repeat count is 751 * greater than 0 or {@link #INFINITE}, the repeat mode will be taken 752 * into account. The repeat count is 0 by default. 753 * 754 * @param value the number of times the animation should be repeated 755 */ 756 public void setRepeatCount(int value) { 757 mRepeatCount = value; 758 } 759 /** 760 * Defines how many times the animation should repeat. The default value 761 * is 0. 762 * 763 * @return the number of times the animation should repeat, or {@link #INFINITE} 764 */ 765 public int getRepeatCount() { 766 return mRepeatCount; 767 } 768 769 /** 770 * Defines what this animation should do when it reaches the end. This 771 * setting is applied only when the repeat count is either greater than 772 * 0 or {@link #INFINITE}. Defaults to {@link #RESTART}. 773 * 774 * @param value {@link #RESTART} or {@link #REVERSE} 775 */ 776 public void setRepeatMode(int value) { 777 mRepeatMode = value; 778 } 779 780 /** 781 * Defines what this animation should do when it reaches the end. 782 * 783 * @return either one of {@link #REVERSE} or {@link #RESTART} 784 */ 785 public int getRepeatMode() { 786 return mRepeatMode; 787 } 788 789 /** 790 * Adds a listener to the set of listeners that are sent update events through the life of 791 * an animation. This method is called on all listeners for every frame of the animation, 792 * after the values for the animation have been calculated. 793 * 794 * @param listener the listener to be added to the current set of listeners for this animation. 795 */ 796 public void addUpdateListener(AnimatorUpdateListener listener) { 797 if (mUpdateListeners == null) { 798 mUpdateListeners = new ArrayList<AnimatorUpdateListener>(); 799 } 800 mUpdateListeners.add(listener); 801 } 802 803 /** 804 * Removes all listeners from the set listening to frame updates for this animation. 805 */ 806 public void removeAllUpdateListeners() { 807 if (mUpdateListeners == null) { 808 return; 809 } 810 mUpdateListeners.clear(); 811 mUpdateListeners = null; 812 } 813 814 /** 815 * Removes a listener from the set listening to frame updates for this animation. 816 * 817 * @param listener the listener to be removed from the current set of update listeners 818 * for this animation. 819 */ 820 public void removeUpdateListener(AnimatorUpdateListener listener) { 821 if (mUpdateListeners == null) { 822 return; 823 } 824 mUpdateListeners.remove(listener); 825 if (mUpdateListeners.size() == 0) { 826 mUpdateListeners = null; 827 } 828 } 829 830 831 /** 832 * The time interpolator used in calculating the elapsed fraction of this animation. The 833 * interpolator determines whether the animation runs with linear or non-linear motion, 834 * such as acceleration and deceleration. The default value is 835 * {@link android.view.animation.AccelerateDecelerateInterpolator} 836 * 837 * @param value the interpolator to be used by this animation. A value of <code>null</code> 838 * will result in linear interpolation. 839 */ 840 @Override 841 public void setInterpolator(TimeInterpolator value) { 842 if (value != null) { 843 mInterpolator = value; 844 } else { 845 mInterpolator = new LinearInterpolator(); 846 } 847 } 848 849 /** 850 * Returns the timing interpolator that this ValueAnimator uses. 851 * 852 * @return The timing interpolator for this ValueAnimator. 853 */ 854 public TimeInterpolator getInterpolator() { 855 return mInterpolator; 856 } 857 858 /** 859 * The type evaluator to be used when calculating the animated values of this animation. 860 * The system will automatically assign a float or int evaluator based on the type 861 * of <code>startValue</code> and <code>endValue</code> in the constructor. But if these values 862 * are not one of these primitive types, or if different evaluation is desired (such as is 863 * necessary with int values that represent colors), a custom evaluator needs to be assigned. 864 * For example, when running an animation on color values, the {@link ArgbEvaluator} 865 * should be used to get correct RGB color interpolation. 866 * 867 * <p>If this ValueAnimator has only one set of values being animated between, this evaluator 868 * will be used for that set. If there are several sets of values being animated, which is 869 * the case if PropertyValuesHOlder objects were set on the ValueAnimator, then the evaluator 870 * is assigned just to the first PropertyValuesHolder object.</p> 871 * 872 * @param value the evaluator to be used this animation 873 */ 874 public void setEvaluator(TypeEvaluator value) { 875 if (value != null && mValues != null && mValues.length > 0) { 876 mValues[0].setEvaluator(value); 877 } 878 } 879 880 /** 881 * Start the animation playing. This version of start() takes a boolean flag that indicates 882 * whether the animation should play in reverse. The flag is usually false, but may be set 883 * to true if called from the reverse() method. 884 * 885 * <p>The animation started by calling this method will be run on the thread that called 886 * this method. This thread should have a Looper on it (a runtime exception will be thrown if 887 * this is not the case). Also, if the animation will animate 888 * properties of objects in the view hierarchy, then the calling thread should be the UI 889 * thread for that view hierarchy.</p> 890 * 891 * @param playBackwards Whether the ValueAnimator should start playing in reverse. 892 */ 893 private void start(boolean playBackwards) { 894 if (Looper.myLooper() == null) { 895 throw new AndroidRuntimeException("Animators may only be run on Looper threads"); 896 } 897 mPlayingBackwards = playBackwards; 898 mCurrentIteration = 0; 899 mPlayingState = STOPPED; 900 mStartedDelay = false; 901 sPendingAnimations.get().add(this); 902 if (mStartDelay == 0) { 903 // This sets the initial value of the animation, prior to actually starting it running 904 setCurrentPlayTime(getCurrentPlayTime()); 905 906 if (mListeners != null) { 907 ArrayList<AnimatorListener> tmpListeners = 908 (ArrayList<AnimatorListener>) mListeners.clone(); 909 int numListeners = tmpListeners.size(); 910 for (int i = 0; i < numListeners; ++i) { 911 tmpListeners.get(i).onAnimationStart(this); 912 } 913 } 914 } 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 } else if (!mInitialized) { 952 initAnimation(); 953 } 954 // The final value set on the target varies, depending on whether the animation 955 // was supposed to repeat an odd number of times 956 if (mRepeatCount > 0 && (mRepeatCount & 0x01) == 1) { 957 animateValue(0f); 958 } else { 959 animateValue(1f); 960 } 961 endAnimation(); 962 } 963 964 @Override 965 public boolean isRunning() { 966 return (mPlayingState == RUNNING); 967 } 968 969 /** 970 * Plays the ValueAnimator in reverse. If the animation is already running, 971 * it will stop itself and play backwards from the point reached when reverse was called. 972 * If the animation is not currently running, then it will start from the end and 973 * play backwards. This behavior is only set for the current animation; future playing 974 * of the animation will use the default behavior of playing forward. 975 */ 976 public void reverse() { 977 mPlayingBackwards = !mPlayingBackwards; 978 if (mPlayingState == RUNNING) { 979 long currentTime = AnimationUtils.currentAnimationTimeMillis(); 980 long currentPlayTime = currentTime - mStartTime; 981 long timeLeft = mDuration - currentPlayTime; 982 mStartTime = currentTime - timeLeft; 983 } else { 984 start(true); 985 } 986 } 987 988 /** 989 * Called internally to end an animation by removing it from the animations list. Must be 990 * called on the UI thread. 991 */ 992 private void endAnimation() { 993 sAnimations.get().remove(this); 994 sPendingAnimations.get().remove(this); 995 sDelayedAnims.get().remove(this); 996 mPlayingState = STOPPED; 997 if (mListeners != null) { 998 ArrayList<AnimatorListener> tmpListeners = 999 (ArrayList<AnimatorListener>) mListeners.clone(); 1000 int numListeners = tmpListeners.size(); 1001 for (int i = 0; i < numListeners; ++i) { 1002 tmpListeners.get(i).onAnimationEnd(this); 1003 } 1004 } 1005 } 1006 1007 /** 1008 * Called internally to start an animation by adding it to the active animations list. Must be 1009 * called on the UI thread. 1010 */ 1011 private void startAnimation() { 1012 initAnimation(); 1013 sAnimations.get().add(this); 1014 if (mStartDelay > 0 && mListeners != null) { 1015 // Listeners were already notified in start() if startDelay is 0; this is 1016 // just for delayed animations 1017 ArrayList<AnimatorListener> tmpListeners = 1018 (ArrayList<AnimatorListener>) mListeners.clone(); 1019 int numListeners = tmpListeners.size(); 1020 for (int i = 0; i < numListeners; ++i) { 1021 tmpListeners.get(i).onAnimationStart(this); 1022 } 1023 } 1024 } 1025 1026 /** 1027 * Internal function called to process an animation frame on an animation that is currently 1028 * sleeping through its <code>startDelay</code> phase. The return value indicates whether it 1029 * should be woken up and put on the active animations queue. 1030 * 1031 * @param currentTime The current animation time, used to calculate whether the animation 1032 * has exceeded its <code>startDelay</code> and should be started. 1033 * @return True if the animation's <code>startDelay</code> has been exceeded and the animation 1034 * should be added to the set of active animations. 1035 */ 1036 private boolean delayedAnimationFrame(long currentTime) { 1037 if (!mStartedDelay) { 1038 mStartedDelay = true; 1039 mDelayStartTime = currentTime; 1040 } else { 1041 long deltaTime = currentTime - mDelayStartTime; 1042 if (deltaTime > mStartDelay) { 1043 // startDelay ended - start the anim and record the 1044 // mStartTime appropriately 1045 mStartTime = currentTime - (deltaTime - mStartDelay); 1046 mPlayingState = RUNNING; 1047 return true; 1048 } 1049 } 1050 return false; 1051 } 1052 1053 /** 1054 * This internal function processes a single animation frame for a given animation. The 1055 * currentTime parameter is the timing pulse sent by the handler, used to calculate the 1056 * elapsed duration, and therefore 1057 * the elapsed fraction, of the animation. The return value indicates whether the animation 1058 * should be ended (which happens when the elapsed time of the animation exceeds the 1059 * animation's duration, including the repeatCount). 1060 * 1061 * @param currentTime The current time, as tracked by the static timing handler 1062 * @return true if the animation's duration, including any repetitions due to 1063 * <code>repeatCount</code> has been exceeded and the animation should be ended. 1064 */ 1065 boolean animationFrame(long currentTime) { 1066 boolean done = false; 1067 1068 if (mPlayingState == STOPPED) { 1069 mPlayingState = RUNNING; 1070 if (mSeekTime < 0) { 1071 mStartTime = currentTime; 1072 } else { 1073 mStartTime = currentTime - mSeekTime; 1074 // Now that we're playing, reset the seek time 1075 mSeekTime = -1; 1076 } 1077 } 1078 switch (mPlayingState) { 1079 case RUNNING: 1080 case SEEKED: 1081 float fraction = mDuration > 0 ? (float)(currentTime - mStartTime) / mDuration : 1f; 1082 if (fraction >= 1f) { 1083 if (mCurrentIteration < mRepeatCount || mRepeatCount == INFINITE) { 1084 // Time to repeat 1085 if (mListeners != null) { 1086 int numListeners = mListeners.size(); 1087 for (int i = 0; i < numListeners; ++i) { 1088 mListeners.get(i).onAnimationRepeat(this); 1089 } 1090 } 1091 if (mRepeatMode == REVERSE) { 1092 mPlayingBackwards = mPlayingBackwards ? false : true; 1093 } 1094 mCurrentIteration += (int)fraction; 1095 fraction = fraction % 1f; 1096 mStartTime += mDuration; 1097 } else { 1098 done = true; 1099 fraction = Math.min(fraction, 1.0f); 1100 } 1101 } 1102 if (mPlayingBackwards) { 1103 fraction = 1f - fraction; 1104 } 1105 animateValue(fraction); 1106 break; 1107 } 1108 1109 return done; 1110 } 1111 1112 /** 1113 * This method is called with the elapsed fraction of the animation during every 1114 * animation frame. This function turns the elapsed fraction into an interpolated fraction 1115 * and then into an animated value (from the evaluator. The function is called mostly during 1116 * animation updates, but it is also called when the <code>end()</code> 1117 * function is called, to set the final value on the property. 1118 * 1119 * <p>Overrides of this method must call the superclass to perform the calculation 1120 * of the animated value.</p> 1121 * 1122 * @param fraction The elapsed fraction of the animation. 1123 */ 1124 void animateValue(float fraction) { 1125 fraction = mInterpolator.getInterpolation(fraction); 1126 int numValues = mValues.length; 1127 for (int i = 0; i < numValues; ++i) { 1128 mValues[i].calculateValue(fraction); 1129 } 1130 if (mUpdateListeners != null) { 1131 int numListeners = mUpdateListeners.size(); 1132 for (int i = 0; i < numListeners; ++i) { 1133 mUpdateListeners.get(i).onAnimationUpdate(this); 1134 } 1135 } 1136 } 1137 1138 @Override 1139 public ValueAnimator clone() { 1140 final ValueAnimator anim = (ValueAnimator) super.clone(); 1141 if (mUpdateListeners != null) { 1142 ArrayList<AnimatorUpdateListener> oldListeners = mUpdateListeners; 1143 anim.mUpdateListeners = new ArrayList<AnimatorUpdateListener>(); 1144 int numListeners = oldListeners.size(); 1145 for (int i = 0; i < numListeners; ++i) { 1146 anim.mUpdateListeners.add(oldListeners.get(i)); 1147 } 1148 } 1149 anim.mSeekTime = -1; 1150 anim.mPlayingBackwards = false; 1151 anim.mCurrentIteration = 0; 1152 anim.mInitialized = false; 1153 anim.mPlayingState = STOPPED; 1154 anim.mStartedDelay = false; 1155 PropertyValuesHolder[] oldValues = mValues; 1156 if (oldValues != null) { 1157 int numValues = oldValues.length; 1158 anim.mValues = new PropertyValuesHolder[numValues]; 1159 for (int i = 0; i < numValues; ++i) { 1160 anim.mValues[i] = oldValues[i].clone(); 1161 } 1162 anim.mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues); 1163 for (int i = 0; i < numValues; ++i) { 1164 PropertyValuesHolder valuesHolder = mValues[i]; 1165 anim.mValuesMap.put(valuesHolder.getPropertyName(), valuesHolder); 1166 } 1167 } 1168 return anim; 1169 } 1170 1171 /** 1172 * Implementors of this interface can add themselves as update listeners 1173 * to an <code>ValueAnimator</code> instance to receive callbacks on every animation 1174 * frame, after the current frame's values have been calculated for that 1175 * <code>ValueAnimator</code>. 1176 */ 1177 public static interface AnimatorUpdateListener { 1178 /** 1179 * <p>Notifies the occurrence of another frame of the animation.</p> 1180 * 1181 * @param animation The animation which was repeated. 1182 */ 1183 void onAnimationUpdate(ValueAnimator animation); 1184 1185 } 1186 1187 /** 1188 * Return the number of animations currently running. 1189 * 1190 * Used by StrictMode internally to annotate violations. Only 1191 * called on the main thread. 1192 * 1193 * @hide 1194 */ 1195 public static int getCurrentAnimationsCount() { 1196 return sAnimations.get().size(); 1197 } 1198 1199 /** 1200 * Clear all animations on this thread, without canceling or ending them. 1201 * This should be used with caution. 1202 * 1203 * @hide 1204 */ 1205 public static void clearAllAnimations() { 1206 sAnimations.get().clear(); 1207 sPendingAnimations.get().clear(); 1208 sDelayedAnims.get().clear(); 1209 } 1210} 1211