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