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