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