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