ValueAnimator.java revision 08c7116ab9cd04ad6dd3c04aa1017237e7f409ac
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.Looper; 20import android.os.Trace; 21import android.util.AndroidRuntimeException; 22import android.view.Choreographer; 23import android.view.animation.AccelerateDecelerateInterpolator; 24import android.view.animation.AnimationUtils; 25import android.view.animation.LinearInterpolator; 26 27import java.util.ArrayList; 28import java.util.HashMap; 29 30/** 31 * This class provides a simple timing engine for running animations 32 * which calculate animated values and set them on target objects. 33 * 34 * <p>There is a single timing pulse that all animations use. It runs in a 35 * custom handler to ensure that property changes happen on the UI thread.</p> 36 * 37 * <p>By default, ValueAnimator uses non-linear time interpolation, via the 38 * {@link AccelerateDecelerateInterpolator} class, which accelerates into and decelerates 39 * out of an animation. This behavior can be changed by calling 40 * {@link ValueAnimator#setInterpolator(TimeInterpolator)}.</p> 41 * 42 * <p>Animators can be created from either code or resource files. Here is an example 43 * of a ValueAnimator resource file:</p> 44 * 45 * {@sample development/samples/ApiDemos/res/anim/animator.xml ValueAnimatorResources} 46 * 47 * <p>It is also possible to use a combination of {@link PropertyValuesHolder} and 48 * {@link Keyframe} resource tags to create a multi-step animation. 49 * Note that you can specify explicit fractional values (from 0 to 1) for 50 * each keyframe to determine when, in the overall duration, the animation should arrive at that 51 * value. Alternatively, you can leave the fractions off and the keyframes will be equally 52 * distributed within the total duration:</p> 53 * 54 * {@sample development/samples/ApiDemos/res/anim/value_animator_pvh_kf.xml 55 * ValueAnimatorKeyframeResources} 56 * 57 * <div class="special reference"> 58 * <h3>Developer Guides</h3> 59 * <p>For more information about animating with {@code ValueAnimator}, read the 60 * <a href="{@docRoot}guide/topics/graphics/prop-animation.html#value-animator">Property 61 * Animation</a> developer guide.</p> 62 * </div> 63 */ 64@SuppressWarnings("unchecked") 65public class ValueAnimator extends Animator { 66 67 /** 68 * Internal constants 69 */ 70 private static float sDurationScale = 1.0f; 71 72 /** 73 * Values used with internal variable mPlayingState to indicate the current state of an 74 * animation. 75 */ 76 static final int STOPPED = 0; // Not yet playing 77 static final int RUNNING = 1; // Playing normally 78 static final int SEEKED = 2; // Seeked to some time value 79 80 /** 81 * Internal variables 82 * NOTE: This object implements the clone() method, making a deep copy of any referenced 83 * objects. As other non-trivial fields are added to this class, make sure to add logic 84 * to clone() to make deep copies of them. 85 */ 86 87 // The first time that the animation's animateFrame() method is called. This time is used to 88 // determine elapsed time (and therefore the elapsed fraction) in subsequent calls 89 // to animateFrame() 90 long mStartTime; 91 92 /** 93 * Set when setCurrentPlayTime() is called. If negative, animation is not currently seeked 94 * to a value. 95 */ 96 float mSeekFraction = -1; 97 98 /** 99 * Set on the next frame after pause() is called, used to calculate a new startTime 100 * or delayStartTime which allows the animator to continue from the point at which 101 * it was paused. If negative, has not yet been set. 102 */ 103 private long mPauseTime; 104 105 /** 106 * Set when an animator is resumed. This triggers logic in the next frame which 107 * actually resumes the animator. 108 */ 109 private boolean mResumed = false; 110 111 112 // The static sAnimationHandler processes the internal timing loop on which all animations 113 // are based 114 /** 115 * @hide 116 */ 117 protected static ThreadLocal<AnimationHandler> sAnimationHandler = 118 new ThreadLocal<AnimationHandler>(); 119 120 // The time interpolator to be used if none is set on the animation 121 private static final TimeInterpolator sDefaultInterpolator = 122 new AccelerateDecelerateInterpolator(); 123 124 /** 125 * Used to indicate whether the animation is currently playing in reverse. This causes the 126 * elapsed fraction to be inverted to calculate the appropriate values. 127 */ 128 private boolean mPlayingBackwards = false; 129 130 /** 131 * Flag to indicate whether this animator is playing in reverse mode, specifically 132 * by being started or interrupted by a call to reverse(). This flag is different than 133 * mPlayingBackwards, which indicates merely whether the current iteration of the 134 * animator is playing in reverse. It is used in corner cases to determine proper end 135 * behavior. 136 */ 137 private boolean mReversing; 138 139 /** 140 * This variable tracks the current iteration that is playing. When mCurrentIteration exceeds the 141 * repeatCount (if repeatCount!=INFINITE), the animation ends 142 */ 143 private int mCurrentIteration = 0; 144 145 /** 146 * Tracks current elapsed/eased fraction, for querying in getAnimatedFraction(). 147 */ 148 private float mCurrentFraction = 0f; 149 150 /** 151 * Tracks whether a startDelay'd animation has begun playing through the startDelay. 152 */ 153 private boolean mStartedDelay = false; 154 155 /** 156 * Tracks the time at which the animation began playing through its startDelay. This is 157 * different from the mStartTime variable, which is used to track when the animation became 158 * active (which is when the startDelay expired and the animation was added to the active 159 * animations list). 160 */ 161 private long mDelayStartTime; 162 163 /** 164 * Flag that represents the current state of the animation. Used to figure out when to start 165 * an animation (if state == STOPPED). Also used to end an animation that 166 * has been cancel()'d or end()'d since the last animation frame. Possible values are 167 * STOPPED, RUNNING, SEEKED. 168 */ 169 int mPlayingState = STOPPED; 170 171 /** 172 * Additional playing state to indicate whether an animator has been start()'d. There is 173 * some lag between a call to start() and the first animation frame. We should still note 174 * that the animation has been started, even if it's first animation frame has not yet 175 * happened, and reflect that state in isRunning(). 176 * Note that delayed animations are different: they are not started until their first 177 * animation frame, which occurs after their delay elapses. 178 */ 179 private boolean mRunning = false; 180 181 /** 182 * Additional playing state to indicate whether an animator has been start()'d, whether or 183 * not there is a nonzero startDelay. 184 */ 185 private boolean mStarted = false; 186 187 /** 188 * Tracks whether we've notified listeners of the onAnimationStart() event. This can be 189 * complex to keep track of since we notify listeners at different times depending on 190 * startDelay and whether start() was called before end(). 191 */ 192 private boolean mStartListenersCalled = false; 193 194 /** 195 * Flag that denotes whether the animation is set up and ready to go. Used to 196 * set up animation that has not yet been started. 197 */ 198 boolean mInitialized = false; 199 200 // 201 // Backing variables 202 // 203 204 // How long the animation should last in ms 205 private long mDuration = (long)(300 * sDurationScale); 206 private long mUnscaledDuration = 300; 207 208 // The amount of time in ms to delay starting the animation after start() is called 209 private long mStartDelay = 0; 210 private long mUnscaledStartDelay = 0; 211 212 // The number of times the animation will repeat. The default is 0, which means the animation 213 // will play only once 214 private int mRepeatCount = 0; 215 216 /** 217 * The type of repetition that will occur when repeatMode is nonzero. RESTART means the 218 * animation will start from the beginning on every new cycle. REVERSE means the animation 219 * will reverse directions on each iteration. 220 */ 221 private int mRepeatMode = RESTART; 222 223 /** 224 * The time interpolator to be used. The elapsed fraction of the animation will be passed 225 * through this interpolator to calculate the interpolated fraction, which is then used to 226 * calculate the animated values. 227 */ 228 private TimeInterpolator mInterpolator = sDefaultInterpolator; 229 230 /** 231 * The set of listeners to be sent events through the life of an animation. 232 */ 233 ArrayList<AnimatorUpdateListener> mUpdateListeners = null; 234 235 /** 236 * The property/value sets being animated. 237 */ 238 PropertyValuesHolder[] mValues; 239 240 /** 241 * A hashmap of the PropertyValuesHolder objects. This map is used to lookup animated values 242 * by property name during calls to getAnimatedValue(String). 243 */ 244 HashMap<String, PropertyValuesHolder> mValuesMap; 245 246 /** 247 * Public constants 248 */ 249 250 /** 251 * When the animation reaches the end and <code>repeatCount</code> is INFINITE 252 * or a positive value, the animation restarts from the beginning. 253 */ 254 public static final int RESTART = 1; 255 /** 256 * When the animation reaches the end and <code>repeatCount</code> is INFINITE 257 * or a positive value, the animation reverses direction on every iteration. 258 */ 259 public static final int REVERSE = 2; 260 /** 261 * This value used used with the {@link #setRepeatCount(int)} property to repeat 262 * the animation indefinitely. 263 */ 264 public static final int INFINITE = -1; 265 266 267 /** 268 * @hide 269 */ 270 public static void setDurationScale(float durationScale) { 271 sDurationScale = durationScale; 272 } 273 274 /** 275 * @hide 276 */ 277 public static float getDurationScale() { 278 return sDurationScale; 279 } 280 281 /** 282 * Creates a new ValueAnimator object. This default constructor is primarily for 283 * use internally; the factory methods which take parameters are more generally 284 * useful. 285 */ 286 public ValueAnimator() { 287 } 288 289 /** 290 * Constructs and returns a ValueAnimator that animates between int values. A single 291 * value implies that that value is the one being animated to. However, this is not typically 292 * useful in a ValueAnimator object because there is no way for the object to determine the 293 * starting value for the animation (unlike ObjectAnimator, which can derive that value 294 * from the target object and property being animated). Therefore, there should typically 295 * be two or more values. 296 * 297 * @param values A set of values that the animation will animate between over time. 298 * @return A ValueAnimator object that is set up to animate between the given values. 299 */ 300 public static ValueAnimator ofInt(int... values) { 301 ValueAnimator anim = new ValueAnimator(); 302 anim.setIntValues(values); 303 return anim; 304 } 305 306 /** 307 * Constructs and returns a ValueAnimator that animates between color values. A single 308 * value implies that that value is the one being animated to. However, this is not typically 309 * useful in a ValueAnimator object because there is no way for the object to determine the 310 * starting value for the animation (unlike ObjectAnimator, which can derive that value 311 * from the target object and property being animated). Therefore, there should typically 312 * be two or more values. 313 * 314 * @param values A set of values that the animation will animate between over time. 315 * @return A ValueAnimator object that is set up to animate between the given values. 316 */ 317 public static ValueAnimator ofArgb(int... values) { 318 ValueAnimator anim = new ValueAnimator(); 319 anim.setIntValues(values); 320 anim.setEvaluator(ArgbEvaluator.getInstance()); 321 return anim; 322 } 323 324 /** 325 * Constructs and returns a ValueAnimator that animates between float values. A single 326 * value implies that that value is the one being animated to. However, this is not typically 327 * useful in a ValueAnimator object because there is no way for the object to determine the 328 * starting value for the animation (unlike ObjectAnimator, which can derive that value 329 * from the target object and property being animated). Therefore, there should typically 330 * be two or more values. 331 * 332 * @param values A set of values that the animation will animate between over time. 333 * @return A ValueAnimator object that is set up to animate between the given values. 334 */ 335 public static ValueAnimator ofFloat(float... values) { 336 ValueAnimator anim = new ValueAnimator(); 337 anim.setFloatValues(values); 338 return anim; 339 } 340 341 /** 342 * Constructs and returns a ValueAnimator that animates between the values 343 * specified in the PropertyValuesHolder objects. 344 * 345 * @param values A set of PropertyValuesHolder objects whose values will be animated 346 * between over time. 347 * @return A ValueAnimator object that is set up to animate between the given values. 348 */ 349 public static ValueAnimator ofPropertyValuesHolder(PropertyValuesHolder... values) { 350 ValueAnimator anim = new ValueAnimator(); 351 anim.setValues(values); 352 return anim; 353 } 354 /** 355 * Constructs and returns a ValueAnimator that animates between Object values. A single 356 * value implies that that value is the one being animated to. However, this is not typically 357 * useful in a ValueAnimator object because there is no way for the object to determine the 358 * starting value for the animation (unlike ObjectAnimator, which can derive that value 359 * from the target object and property being animated). Therefore, there should typically 360 * be two or more values. 361 * 362 * <p>Since ValueAnimator does not know how to animate between arbitrary Objects, this 363 * factory method also takes a TypeEvaluator object that the ValueAnimator will use 364 * to perform that interpolation. 365 * 366 * @param evaluator A TypeEvaluator that will be called on each animation frame to 367 * provide the ncessry interpolation between the Object values to derive the animated 368 * value. 369 * @param values A set of values that the animation will animate between over time. 370 * @return A ValueAnimator object that is set up to animate between the given values. 371 */ 372 public static ValueAnimator ofObject(TypeEvaluator evaluator, Object... values) { 373 ValueAnimator anim = new ValueAnimator(); 374 anim.setObjectValues(values); 375 anim.setEvaluator(evaluator); 376 return anim; 377 } 378 379 /** 380 * Sets int values that will be animated between. A single 381 * value implies that that value is the one being animated to. However, this is not typically 382 * useful in a ValueAnimator object because there is no way for the object to determine the 383 * starting value for the animation (unlike ObjectAnimator, which can derive that value 384 * from the target object and property being animated). Therefore, there should typically 385 * be two or more values. 386 * 387 * <p>If there are already multiple sets of values defined for this ValueAnimator via more 388 * than one PropertyValuesHolder object, this method will set the values for the first 389 * of those objects.</p> 390 * 391 * @param values A set of values that the animation will animate between over time. 392 */ 393 public void setIntValues(int... values) { 394 if (values == null || values.length == 0) { 395 return; 396 } 397 if (mValues == null || mValues.length == 0) { 398 setValues(PropertyValuesHolder.ofInt("", values)); 399 } else { 400 PropertyValuesHolder valuesHolder = mValues[0]; 401 valuesHolder.setIntValues(values); 402 } 403 // New property/values/target should cause re-initialization prior to starting 404 mInitialized = false; 405 } 406 407 /** 408 * Sets float values that will be animated between. A single 409 * value implies that that value is the one being animated to. However, this is not typically 410 * useful in a ValueAnimator object because there is no way for the object to determine the 411 * starting value for the animation (unlike ObjectAnimator, which can derive that value 412 * from the target object and property being animated). Therefore, there should typically 413 * be two or more values. 414 * 415 * <p>If there are already multiple sets of values defined for this ValueAnimator via more 416 * than one PropertyValuesHolder object, this method will set the values for the first 417 * of those objects.</p> 418 * 419 * @param values A set of values that the animation will animate between over time. 420 */ 421 public void setFloatValues(float... values) { 422 if (values == null || values.length == 0) { 423 return; 424 } 425 if (mValues == null || mValues.length == 0) { 426 setValues(PropertyValuesHolder.ofFloat("", values)); 427 } else { 428 PropertyValuesHolder valuesHolder = mValues[0]; 429 valuesHolder.setFloatValues(values); 430 } 431 // New property/values/target should cause re-initialization prior to starting 432 mInitialized = false; 433 } 434 435 /** 436 * Sets the values to animate between for this animation. A single 437 * value implies that that value is the one being animated to. However, this is not typically 438 * useful in a ValueAnimator object because there is no way for the object to determine the 439 * starting value for the animation (unlike ObjectAnimator, which can derive that value 440 * from the target object and property being animated). Therefore, there should typically 441 * be two or more values. 442 * 443 * <p>If there are already multiple sets of values defined for this ValueAnimator via more 444 * than one PropertyValuesHolder object, this method will set the values for the first 445 * of those objects.</p> 446 * 447 * <p>There should be a TypeEvaluator set on the ValueAnimator that knows how to interpolate 448 * between these value objects. ValueAnimator only knows how to interpolate between the 449 * primitive types specified in the other setValues() methods.</p> 450 * 451 * @param values The set of values to animate between. 452 */ 453 public void setObjectValues(Object... values) { 454 if (values == null || values.length == 0) { 455 return; 456 } 457 if (mValues == null || mValues.length == 0) { 458 setValues(PropertyValuesHolder.ofObject("", null, values)); 459 } else { 460 PropertyValuesHolder valuesHolder = mValues[0]; 461 valuesHolder.setObjectValues(values); 462 } 463 // New property/values/target should cause re-initialization prior to starting 464 mInitialized = false; 465 } 466 467 /** 468 * Sets the values, per property, being animated between. This function is called internally 469 * by the constructors of ValueAnimator that take a list of values. But a ValueAnimator can 470 * be constructed without values and this method can be called to set the values manually 471 * instead. 472 * 473 * @param values The set of values, per property, being animated between. 474 */ 475 public void setValues(PropertyValuesHolder... values) { 476 int numValues = values.length; 477 mValues = values; 478 mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues); 479 for (int i = 0; i < numValues; ++i) { 480 PropertyValuesHolder valuesHolder = values[i]; 481 mValuesMap.put(valuesHolder.getPropertyName(), valuesHolder); 482 } 483 // New property/values/target should cause re-initialization prior to starting 484 mInitialized = false; 485 } 486 487 /** 488 * Returns the values that this ValueAnimator animates between. These values are stored in 489 * PropertyValuesHolder objects, even if the ValueAnimator was created with a simple list 490 * of value objects instead. 491 * 492 * @return PropertyValuesHolder[] An array of PropertyValuesHolder objects which hold the 493 * values, per property, that define the animation. 494 */ 495 public PropertyValuesHolder[] getValues() { 496 return mValues; 497 } 498 499 /** 500 * This function is called immediately before processing the first animation 501 * frame of an animation. If there is a nonzero <code>startDelay</code>, the 502 * function is called after that delay ends. 503 * It takes care of the final initialization steps for the 504 * animation. 505 * 506 * <p>Overrides of this method should call the superclass method to ensure 507 * that internal mechanisms for the animation are set up correctly.</p> 508 */ 509 void initAnimation() { 510 if (!mInitialized) { 511 int numValues = mValues.length; 512 for (int i = 0; i < numValues; ++i) { 513 mValues[i].init(); 514 } 515 mInitialized = true; 516 } 517 } 518 519 520 /** 521 * Sets the length of the animation. The default duration is 300 milliseconds. 522 * 523 * @param duration The length of the animation, in milliseconds. This value cannot 524 * be negative. 525 * @return ValueAnimator The object called with setDuration(). This return 526 * value makes it easier to compose statements together that construct and then set the 527 * duration, as in <code>ValueAnimator.ofInt(0, 10).setDuration(500).start()</code>. 528 */ 529 public ValueAnimator setDuration(long duration) { 530 if (duration < 0) { 531 throw new IllegalArgumentException("Animators cannot have negative duration: " + 532 duration); 533 } 534 mUnscaledDuration = duration; 535 updateScaledDuration(); 536 return this; 537 } 538 539 private void updateScaledDuration() { 540 mDuration = (long)(mUnscaledDuration * sDurationScale); 541 } 542 543 /** 544 * Gets the length of the animation. The default duration is 300 milliseconds. 545 * 546 * @return The length of the animation, in milliseconds. 547 */ 548 public long getDuration() { 549 return mUnscaledDuration; 550 } 551 552 /** 553 * Sets the position of the animation to the specified point in time. This time should 554 * be between 0 and the total duration of the animation, including any repetition. If 555 * the animation has not yet been started, then it will not advance forward after it is 556 * set to this time; it will simply set the time to this value and perform any appropriate 557 * actions based on that time. If the animation is already running, then setCurrentPlayTime() 558 * will set the current playing time to this value and continue playing from that point. 559 * 560 * @param playTime The time, in milliseconds, to which the animation is advanced or rewound. 561 */ 562 public void setCurrentPlayTime(long playTime) { 563 float fraction = mUnscaledDuration > 0 ? (float) playTime / mUnscaledDuration : 1; 564 setCurrentFraction(fraction); 565 } 566 567 /** 568 * Sets the position of the animation to the specified fraction. This fraction should 569 * be between 0 and the total fraction of the animation, including any repetition. That is, 570 * a fraction of 0 will position the animation at the beginning, a value of 1 at the end, 571 * and a value of 2 at the end of a reversing animator that repeats once. If 572 * the animation has not yet been started, then it will not advance forward after it is 573 * set to this fraction; it will simply set the fraction to this value and perform any 574 * appropriate actions based on that fraction. If the animation is already running, then 575 * setCurrentFraction() will set the current fraction to this value and continue 576 * playing from that point. {@link Animator.AnimatorListener} events are not called 577 * due to changing the fraction; those events are only processed while the animation 578 * is running. 579 * 580 * @param fraction The fraction to which the animation is advanced or rewound. Values 581 * outside the range of 0 to the maximum fraction for the animator will be clamped to 582 * the correct range. 583 */ 584 public void setCurrentFraction(float fraction) { 585 initAnimation(); 586 if (fraction < 0) { 587 fraction = 0; 588 } 589 int iteration = (int) fraction; 590 if (fraction == 1) { 591 iteration -= 1; 592 } else if (fraction > 1) { 593 if (iteration < (mRepeatCount + 1) || mRepeatCount == INFINITE) { 594 if (mRepeatMode == REVERSE) { 595 mPlayingBackwards = (iteration % 2) != 0; 596 } 597 fraction = fraction % 1f; 598 } else { 599 fraction = 1; 600 iteration -= 1; 601 } 602 } else { 603 mPlayingBackwards = mReversing; 604 } 605 mCurrentIteration = iteration; 606 long seekTime = (long) (mDuration * fraction); 607 long currentTime = AnimationUtils.currentAnimationTimeMillis(); 608 mStartTime = currentTime - seekTime; 609 if (mPlayingState != RUNNING) { 610 mSeekFraction = fraction; 611 mPlayingState = SEEKED; 612 } 613 if (mPlayingBackwards) { 614 fraction = 1f - fraction; 615 } 616 animateValue(fraction); 617 } 618 619 /** 620 * Gets the current position of the animation in time, which is equal to the current 621 * time minus the time that the animation started. An animation that is not yet started will 622 * return a value of zero. 623 * 624 * @return The current position in time of the animation. 625 */ 626 public long getCurrentPlayTime() { 627 if (!mInitialized || mPlayingState == STOPPED) { 628 return 0; 629 } 630 return AnimationUtils.currentAnimationTimeMillis() - mStartTime; 631 } 632 633 /** 634 * This custom, static handler handles the timing pulse that is shared by 635 * all active animations. This approach ensures that the setting of animation 636 * values will happen on the UI thread and that all animations will share 637 * the same times for calculating their values, which makes synchronizing 638 * animations possible. 639 * 640 * The handler uses the Choreographer for executing periodic callbacks. 641 * 642 * @hide 643 */ 644 @SuppressWarnings("unchecked") 645 protected static class AnimationHandler implements Runnable { 646 // The per-thread list of all active animations 647 /** @hide */ 648 protected final ArrayList<ValueAnimator> mAnimations = new ArrayList<ValueAnimator>(); 649 650 // Used in doAnimationFrame() to avoid concurrent modifications of mAnimations 651 private final ArrayList<ValueAnimator> mTmpAnimations = new ArrayList<ValueAnimator>(); 652 653 // The per-thread set of animations to be started on the next animation frame 654 /** @hide */ 655 protected final ArrayList<ValueAnimator> mPendingAnimations = new ArrayList<ValueAnimator>(); 656 657 /** 658 * Internal per-thread collections used to avoid set collisions as animations start and end 659 * while being processed. 660 * @hide 661 */ 662 protected final ArrayList<ValueAnimator> mDelayedAnims = new ArrayList<ValueAnimator>(); 663 private final ArrayList<ValueAnimator> mEndingAnims = new ArrayList<ValueAnimator>(); 664 private final ArrayList<ValueAnimator> mReadyAnims = new ArrayList<ValueAnimator>(); 665 666 private final Choreographer mChoreographer; 667 private boolean mAnimationScheduled; 668 669 private AnimationHandler() { 670 mChoreographer = Choreographer.getInstance(); 671 } 672 673 /** 674 * Start animating on the next frame. 675 */ 676 public void start() { 677 scheduleAnimation(); 678 } 679 680 private void doAnimationFrame(long frameTime) { 681 // mPendingAnimations holds any animations that have requested to be started 682 // We're going to clear mPendingAnimations, but starting animation may 683 // cause more to be added to the pending list (for example, if one animation 684 // starting triggers another starting). So we loop until mPendingAnimations 685 // is empty. 686 while (mPendingAnimations.size() > 0) { 687 ArrayList<ValueAnimator> pendingCopy = 688 (ArrayList<ValueAnimator>) mPendingAnimations.clone(); 689 mPendingAnimations.clear(); 690 int count = pendingCopy.size(); 691 for (int i = 0; i < count; ++i) { 692 ValueAnimator anim = pendingCopy.get(i); 693 // If the animation has a startDelay, place it on the delayed list 694 if (anim.mStartDelay == 0) { 695 anim.startAnimation(this); 696 } else { 697 mDelayedAnims.add(anim); 698 } 699 } 700 } 701 // Next, process animations currently sitting on the delayed queue, adding 702 // them to the active animations if they are ready 703 int numDelayedAnims = mDelayedAnims.size(); 704 for (int i = 0; i < numDelayedAnims; ++i) { 705 ValueAnimator anim = mDelayedAnims.get(i); 706 if (anim.delayedAnimationFrame(frameTime)) { 707 mReadyAnims.add(anim); 708 } 709 } 710 int numReadyAnims = mReadyAnims.size(); 711 if (numReadyAnims > 0) { 712 for (int i = 0; i < numReadyAnims; ++i) { 713 ValueAnimator anim = mReadyAnims.get(i); 714 anim.startAnimation(this); 715 anim.mRunning = true; 716 mDelayedAnims.remove(anim); 717 } 718 mReadyAnims.clear(); 719 } 720 721 // Now process all active animations. The return value from animationFrame() 722 // tells the handler whether it should now be ended 723 int numAnims = mAnimations.size(); 724 for (int i = 0; i < numAnims; ++i) { 725 mTmpAnimations.add(mAnimations.get(i)); 726 } 727 for (int i = 0; i < numAnims; ++i) { 728 ValueAnimator anim = mTmpAnimations.get(i); 729 if (mAnimations.contains(anim) && anim.doAnimationFrame(frameTime)) { 730 mEndingAnims.add(anim); 731 } 732 } 733 mTmpAnimations.clear(); 734 if (mEndingAnims.size() > 0) { 735 for (int i = 0; i < mEndingAnims.size(); ++i) { 736 mEndingAnims.get(i).endAnimation(this); 737 } 738 mEndingAnims.clear(); 739 } 740 741 // If there are still active or delayed animations, schedule a future call to 742 // onAnimate to process the next frame of the animations. 743 if (!mAnimations.isEmpty() || !mDelayedAnims.isEmpty()) { 744 scheduleAnimation(); 745 } 746 } 747 748 // Called by the Choreographer. 749 @Override 750 public void run() { 751 mAnimationScheduled = false; 752 doAnimationFrame(mChoreographer.getFrameTime()); 753 } 754 755 private void scheduleAnimation() { 756 if (!mAnimationScheduled) { 757 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null); 758 mAnimationScheduled = true; 759 } 760 } 761 } 762 763 /** 764 * The amount of time, in milliseconds, to delay starting the animation after 765 * {@link #start()} is called. 766 * 767 * @return the number of milliseconds to delay running the animation 768 */ 769 public long getStartDelay() { 770 return mUnscaledStartDelay; 771 } 772 773 /** 774 * The amount of time, in milliseconds, to delay starting the animation after 775 * {@link #start()} is called. 776 777 * @param startDelay The amount of the delay, in milliseconds 778 */ 779 public void setStartDelay(long startDelay) { 780 this.mStartDelay = (long)(startDelay * sDurationScale); 781 mUnscaledStartDelay = startDelay; 782 } 783 784 /** 785 * The amount of time, in milliseconds, between each frame of the animation. This is a 786 * requested time that the animation will attempt to honor, but the actual delay between 787 * frames may be different, depending on system load and capabilities. This is a static 788 * function because the same delay will be applied to all animations, since they are all 789 * run off of a single timing loop. 790 * 791 * The frame delay may be ignored when the animation system uses an external timing 792 * source, such as the display refresh rate (vsync), to govern animations. 793 * 794 * @return the requested time between frames, in milliseconds 795 */ 796 public static long getFrameDelay() { 797 return Choreographer.getFrameDelay(); 798 } 799 800 /** 801 * The amount of time, in milliseconds, between each frame of the animation. This is a 802 * requested time that the animation will attempt to honor, but the actual delay between 803 * frames may be different, depending on system load and capabilities. This is a static 804 * function because the same delay will be applied to all animations, since they are all 805 * run off of a single timing loop. 806 * 807 * The frame delay may be ignored when the animation system uses an external timing 808 * source, such as the display refresh rate (vsync), to govern animations. 809 * 810 * @param frameDelay the requested time between frames, in milliseconds 811 */ 812 public static void setFrameDelay(long frameDelay) { 813 Choreographer.setFrameDelay(frameDelay); 814 } 815 816 /** 817 * The most recent value calculated by this <code>ValueAnimator</code> when there is just one 818 * property being animated. This value is only sensible while the animation is running. The main 819 * purpose for this read-only property is to retrieve the value from the <code>ValueAnimator</code> 820 * during a call to {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which 821 * is called during each animation frame, immediately after the value is calculated. 822 * 823 * @return animatedValue The value most recently calculated by this <code>ValueAnimator</code> for 824 * the single property being animated. If there are several properties being animated 825 * (specified by several PropertyValuesHolder objects in the constructor), this function 826 * returns the animated value for the first of those objects. 827 */ 828 public Object getAnimatedValue() { 829 if (mValues != null && mValues.length > 0) { 830 return mValues[0].getAnimatedValue(); 831 } 832 // Shouldn't get here; should always have values unless ValueAnimator was set up wrong 833 return null; 834 } 835 836 /** 837 * The most recent value calculated by this <code>ValueAnimator</code> for <code>propertyName</code>. 838 * The main purpose for this read-only property is to retrieve the value from the 839 * <code>ValueAnimator</code> during a call to 840 * {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which 841 * is called during each animation frame, immediately after the value is calculated. 842 * 843 * @return animatedValue The value most recently calculated for the named property 844 * by this <code>ValueAnimator</code>. 845 */ 846 public Object getAnimatedValue(String propertyName) { 847 PropertyValuesHolder valuesHolder = mValuesMap.get(propertyName); 848 if (valuesHolder != null) { 849 return valuesHolder.getAnimatedValue(); 850 } else { 851 // At least avoid crashing if called with bogus propertyName 852 return null; 853 } 854 } 855 856 /** 857 * Sets how many times the animation should be repeated. If the repeat 858 * count is 0, the animation is never repeated. If the repeat count is 859 * greater than 0 or {@link #INFINITE}, the repeat mode will be taken 860 * into account. The repeat count is 0 by default. 861 * 862 * @param value the number of times the animation should be repeated 863 */ 864 public void setRepeatCount(int value) { 865 mRepeatCount = value; 866 } 867 /** 868 * Defines how many times the animation should repeat. The default value 869 * is 0. 870 * 871 * @return the number of times the animation should repeat, or {@link #INFINITE} 872 */ 873 public int getRepeatCount() { 874 return mRepeatCount; 875 } 876 877 /** 878 * Defines what this animation should do when it reaches the end. This 879 * setting is applied only when the repeat count is either greater than 880 * 0 or {@link #INFINITE}. Defaults to {@link #RESTART}. 881 * 882 * @param value {@link #RESTART} or {@link #REVERSE} 883 */ 884 public void setRepeatMode(int value) { 885 mRepeatMode = value; 886 } 887 888 /** 889 * Defines what this animation should do when it reaches the end. 890 * 891 * @return either one of {@link #REVERSE} or {@link #RESTART} 892 */ 893 public int getRepeatMode() { 894 return mRepeatMode; 895 } 896 897 /** 898 * Adds a listener to the set of listeners that are sent update events through the life of 899 * an animation. This method is called on all listeners for every frame of the animation, 900 * after the values for the animation have been calculated. 901 * 902 * @param listener the listener to be added to the current set of listeners for this animation. 903 */ 904 public void addUpdateListener(AnimatorUpdateListener listener) { 905 if (mUpdateListeners == null) { 906 mUpdateListeners = new ArrayList<AnimatorUpdateListener>(); 907 } 908 mUpdateListeners.add(listener); 909 } 910 911 /** 912 * Removes all listeners from the set listening to frame updates for this animation. 913 */ 914 public void removeAllUpdateListeners() { 915 if (mUpdateListeners == null) { 916 return; 917 } 918 mUpdateListeners.clear(); 919 mUpdateListeners = null; 920 } 921 922 /** 923 * Removes a listener from the set listening to frame updates for this animation. 924 * 925 * @param listener the listener to be removed from the current set of update listeners 926 * for this animation. 927 */ 928 public void removeUpdateListener(AnimatorUpdateListener listener) { 929 if (mUpdateListeners == null) { 930 return; 931 } 932 mUpdateListeners.remove(listener); 933 if (mUpdateListeners.size() == 0) { 934 mUpdateListeners = null; 935 } 936 } 937 938 939 /** 940 * The time interpolator used in calculating the elapsed fraction of this animation. The 941 * interpolator determines whether the animation runs with linear or non-linear motion, 942 * such as acceleration and deceleration. The default value is 943 * {@link android.view.animation.AccelerateDecelerateInterpolator} 944 * 945 * @param value the interpolator to be used by this animation. A value of <code>null</code> 946 * will result in linear interpolation. 947 */ 948 @Override 949 public void setInterpolator(TimeInterpolator value) { 950 if (value != null) { 951 mInterpolator = value; 952 } else { 953 mInterpolator = new LinearInterpolator(); 954 } 955 } 956 957 /** 958 * Returns the timing interpolator that this ValueAnimator uses. 959 * 960 * @return The timing interpolator for this ValueAnimator. 961 */ 962 @Override 963 public TimeInterpolator getInterpolator() { 964 return mInterpolator; 965 } 966 967 /** 968 * The type evaluator to be used when calculating the animated values of this animation. 969 * The system will automatically assign a float or int evaluator based on the type 970 * of <code>startValue</code> and <code>endValue</code> in the constructor. But if these values 971 * are not one of these primitive types, or if different evaluation is desired (such as is 972 * necessary with int values that represent colors), a custom evaluator needs to be assigned. 973 * For example, when running an animation on color values, the {@link ArgbEvaluator} 974 * should be used to get correct RGB color interpolation. 975 * 976 * <p>If this ValueAnimator has only one set of values being animated between, this evaluator 977 * will be used for that set. If there are several sets of values being animated, which is 978 * the case if PropertyValuesHolder objects were set on the ValueAnimator, then the evaluator 979 * is assigned just to the first PropertyValuesHolder object.</p> 980 * 981 * @param value the evaluator to be used this animation 982 */ 983 public void setEvaluator(TypeEvaluator value) { 984 if (value != null && mValues != null && mValues.length > 0) { 985 mValues[0].setEvaluator(value); 986 } 987 } 988 989 private void notifyStartListeners() { 990 if (mListeners != null && !mStartListenersCalled) { 991 ArrayList<AnimatorListener> tmpListeners = 992 (ArrayList<AnimatorListener>) mListeners.clone(); 993 int numListeners = tmpListeners.size(); 994 for (int i = 0; i < numListeners; ++i) { 995 tmpListeners.get(i).onAnimationStart(this); 996 } 997 } 998 mStartListenersCalled = true; 999 } 1000 1001 /** 1002 * Start the animation playing. This version of start() takes a boolean flag that indicates 1003 * whether the animation should play in reverse. The flag is usually false, but may be set 1004 * to true if called from the reverse() method. 1005 * 1006 * <p>The animation started by calling this method will be run on the thread that called 1007 * this method. This thread should have a Looper on it (a runtime exception will be thrown if 1008 * this is not the case). Also, if the animation will animate 1009 * properties of objects in the view hierarchy, then the calling thread should be the UI 1010 * thread for that view hierarchy.</p> 1011 * 1012 * @param playBackwards Whether the ValueAnimator should start playing in reverse. 1013 */ 1014 private void start(boolean playBackwards) { 1015 if (Looper.myLooper() == null) { 1016 throw new AndroidRuntimeException("Animators may only be run on Looper threads"); 1017 } 1018 mReversing = playBackwards; 1019 mPlayingBackwards = playBackwards; 1020 if (playBackwards && mSeekFraction != -1) { 1021 if (mSeekFraction == 0 && mCurrentIteration == 0) { 1022 // special case: reversing from seek-to-0 should act as if not seeked at all 1023 mSeekFraction = 0; 1024 } else if (mRepeatCount == INFINITE) { 1025 mSeekFraction = 1 - (mSeekFraction % 1); 1026 } else { 1027 mSeekFraction = 1 + mRepeatCount - (mCurrentIteration + mSeekFraction); 1028 } 1029 mCurrentIteration = (int) mSeekFraction; 1030 mSeekFraction = mSeekFraction % 1; 1031 } 1032 if (mCurrentIteration > 0 && mRepeatMode == REVERSE && 1033 (mCurrentIteration < (mRepeatCount + 1) || mRepeatCount == INFINITE)) { 1034 // if we were seeked to some other iteration in a reversing animator, 1035 // figure out the correct direction to start playing based on the iteration 1036 if (playBackwards) { 1037 mPlayingBackwards = (mCurrentIteration % 2) == 0; 1038 } else { 1039 mPlayingBackwards = (mCurrentIteration % 2) != 0; 1040 } 1041 } 1042 int prevPlayingState = mPlayingState; 1043 mPlayingState = STOPPED; 1044 mStarted = true; 1045 mStartedDelay = false; 1046 mPaused = false; 1047 updateScaledDuration(); // in case the scale factor has changed since creation time 1048 AnimationHandler animationHandler = getOrCreateAnimationHandler(); 1049 animationHandler.mPendingAnimations.add(this); 1050 if (mStartDelay == 0) { 1051 // This sets the initial value of the animation, prior to actually starting it running 1052 if (prevPlayingState != SEEKED) { 1053 setCurrentPlayTime(0); 1054 } 1055 mPlayingState = STOPPED; 1056 mRunning = true; 1057 notifyStartListeners(); 1058 } 1059 animationHandler.start(); 1060 } 1061 1062 @Override 1063 public void start() { 1064 start(false); 1065 } 1066 1067 @Override 1068 public void cancel() { 1069 // Only cancel if the animation is actually running or has been started and is about 1070 // to run 1071 AnimationHandler handler = getOrCreateAnimationHandler(); 1072 if (mPlayingState != STOPPED 1073 || handler.mPendingAnimations.contains(this) 1074 || handler.mDelayedAnims.contains(this)) { 1075 // Only notify listeners if the animator has actually started 1076 if ((mStarted || mRunning) && mListeners != null) { 1077 if (!mRunning) { 1078 // If it's not yet running, then start listeners weren't called. Call them now. 1079 notifyStartListeners(); 1080 } 1081 ArrayList<AnimatorListener> tmpListeners = 1082 (ArrayList<AnimatorListener>) mListeners.clone(); 1083 for (AnimatorListener listener : tmpListeners) { 1084 listener.onAnimationCancel(this); 1085 } 1086 } 1087 endAnimation(handler); 1088 } 1089 } 1090 1091 @Override 1092 public void end() { 1093 AnimationHandler handler = getOrCreateAnimationHandler(); 1094 if (!handler.mAnimations.contains(this) && !handler.mPendingAnimations.contains(this)) { 1095 // Special case if the animation has not yet started; get it ready for ending 1096 mStartedDelay = false; 1097 startAnimation(handler); 1098 mStarted = true; 1099 } else if (!mInitialized) { 1100 initAnimation(); 1101 } 1102 animateValue(mPlayingBackwards ? 0f : 1f); 1103 endAnimation(handler); 1104 } 1105 1106 @Override 1107 public void resume() { 1108 if (mPaused) { 1109 mResumed = true; 1110 } 1111 super.resume(); 1112 } 1113 1114 @Override 1115 public void pause() { 1116 boolean previouslyPaused = mPaused; 1117 super.pause(); 1118 if (!previouslyPaused && mPaused) { 1119 mPauseTime = -1; 1120 mResumed = false; 1121 } 1122 } 1123 1124 @Override 1125 public boolean isRunning() { 1126 return (mPlayingState == RUNNING || mRunning); 1127 } 1128 1129 @Override 1130 public boolean isStarted() { 1131 return mStarted; 1132 } 1133 1134 /** 1135 * Plays the ValueAnimator in reverse. If the animation is already running, 1136 * it will stop itself and play backwards from the point reached when reverse was called. 1137 * If the animation is not currently running, then it will start from the end and 1138 * play backwards. This behavior is only set for the current animation; future playing 1139 * of the animation will use the default behavior of playing forward. 1140 */ 1141 @Override 1142 public void reverse() { 1143 mPlayingBackwards = !mPlayingBackwards; 1144 if (mPlayingState == RUNNING) { 1145 long currentTime = AnimationUtils.currentAnimationTimeMillis(); 1146 long currentPlayTime = currentTime - mStartTime; 1147 long timeLeft = mDuration - currentPlayTime; 1148 mStartTime = currentTime - timeLeft; 1149 mReversing = !mReversing; 1150 } else if (mStarted) { 1151 end(); 1152 } else { 1153 start(true); 1154 } 1155 } 1156 1157 /** 1158 * @hide 1159 */ 1160 @Override 1161 public boolean canReverse() { 1162 return true; 1163 } 1164 1165 /** 1166 * Called internally to end an animation by removing it from the animations list. Must be 1167 * called on the UI thread. 1168 * @hide 1169 */ 1170 protected void endAnimation(AnimationHandler handler) { 1171 handler.mAnimations.remove(this); 1172 handler.mPendingAnimations.remove(this); 1173 handler.mDelayedAnims.remove(this); 1174 mPlayingState = STOPPED; 1175 mPaused = false; 1176 if ((mStarted || mRunning) && mListeners != null) { 1177 if (!mRunning) { 1178 // If it's not yet running, then start listeners weren't called. Call them now. 1179 notifyStartListeners(); 1180 } 1181 ArrayList<AnimatorListener> tmpListeners = 1182 (ArrayList<AnimatorListener>) mListeners.clone(); 1183 int numListeners = tmpListeners.size(); 1184 for (int i = 0; i < numListeners; ++i) { 1185 tmpListeners.get(i).onAnimationEnd(this); 1186 } 1187 } 1188 mRunning = false; 1189 mStarted = false; 1190 mStartListenersCalled = false; 1191 mPlayingBackwards = false; 1192 mReversing = false; 1193 mCurrentIteration = 0; 1194 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 1195 Trace.asyncTraceEnd(Trace.TRACE_TAG_VIEW, getNameForTrace(), 1196 System.identityHashCode(this)); 1197 } 1198 } 1199 1200 /** 1201 * Called internally to start an animation by adding it to the active animations list. Must be 1202 * called on the UI thread. 1203 */ 1204 private void startAnimation(AnimationHandler handler) { 1205 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 1206 Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, getNameForTrace(), 1207 System.identityHashCode(this)); 1208 } 1209 initAnimation(); 1210 handler.mAnimations.add(this); 1211 if (mStartDelay > 0 && mListeners != null) { 1212 // Listeners were already notified in start() if startDelay is 0; this is 1213 // just for delayed animations 1214 notifyStartListeners(); 1215 } 1216 } 1217 1218 /** 1219 * Returns the name of this animator for debugging purposes. 1220 */ 1221 String getNameForTrace() { 1222 return "animator"; 1223 } 1224 1225 1226 /** 1227 * Internal function called to process an animation frame on an animation that is currently 1228 * sleeping through its <code>startDelay</code> phase. The return value indicates whether it 1229 * should be woken up and put on the active animations queue. 1230 * 1231 * @param currentTime The current animation time, used to calculate whether the animation 1232 * has exceeded its <code>startDelay</code> and should be started. 1233 * @return True if the animation's <code>startDelay</code> has been exceeded and the animation 1234 * should be added to the set of active animations. 1235 */ 1236 private boolean delayedAnimationFrame(long currentTime) { 1237 if (!mStartedDelay) { 1238 mStartedDelay = true; 1239 mDelayStartTime = currentTime; 1240 } 1241 if (mPaused) { 1242 if (mPauseTime < 0) { 1243 mPauseTime = currentTime; 1244 } 1245 return false; 1246 } else if (mResumed) { 1247 mResumed = false; 1248 if (mPauseTime > 0) { 1249 // Offset by the duration that the animation was paused 1250 mDelayStartTime += (currentTime - mPauseTime); 1251 } 1252 } 1253 long deltaTime = currentTime - mDelayStartTime; 1254 if (deltaTime > mStartDelay) { 1255 // startDelay ended - start the anim and record the 1256 // mStartTime appropriately 1257 mStartTime = currentTime - (deltaTime - mStartDelay); 1258 mPlayingState = RUNNING; 1259 return true; 1260 } 1261 return false; 1262 } 1263 1264 /** 1265 * This internal function processes a single animation frame for a given animation. The 1266 * currentTime parameter is the timing pulse sent by the handler, used to calculate the 1267 * elapsed duration, and therefore 1268 * the elapsed fraction, of the animation. The return value indicates whether the animation 1269 * should be ended (which happens when the elapsed time of the animation exceeds the 1270 * animation's duration, including the repeatCount). 1271 * 1272 * @param currentTime The current time, as tracked by the static timing handler 1273 * @return true if the animation's duration, including any repetitions due to 1274 * <code>repeatCount</code>, has been exceeded and the animation should be ended. 1275 */ 1276 boolean animationFrame(long currentTime) { 1277 boolean done = false; 1278 switch (mPlayingState) { 1279 case RUNNING: 1280 case SEEKED: 1281 float fraction = mDuration > 0 ? (float)(currentTime - mStartTime) / mDuration : 1f; 1282 if (mDuration == 0 && mRepeatCount != INFINITE) { 1283 // Skip to the end 1284 mCurrentIteration = mRepeatCount; 1285 if (!mReversing) { 1286 mPlayingBackwards = false; 1287 } 1288 } 1289 if (fraction >= 1f) { 1290 if (mCurrentIteration < mRepeatCount || mRepeatCount == INFINITE) { 1291 // Time to repeat 1292 if (mListeners != null) { 1293 int numListeners = mListeners.size(); 1294 for (int i = 0; i < numListeners; ++i) { 1295 mListeners.get(i).onAnimationRepeat(this); 1296 } 1297 } 1298 if (mRepeatMode == REVERSE) { 1299 mPlayingBackwards = !mPlayingBackwards; 1300 } 1301 mCurrentIteration += (int) fraction; 1302 fraction = fraction % 1f; 1303 mStartTime += mDuration; 1304 } else { 1305 done = true; 1306 fraction = Math.min(fraction, 1.0f); 1307 } 1308 } 1309 if (mPlayingBackwards) { 1310 fraction = 1f - fraction; 1311 } 1312 animateValue(fraction); 1313 break; 1314 } 1315 1316 return done; 1317 } 1318 1319 /** 1320 * Processes a frame of the animation, adjusting the start time if needed. 1321 * 1322 * @param frameTime The frame time. 1323 * @return true if the animation has ended. 1324 */ 1325 final boolean doAnimationFrame(long frameTime) { 1326 if (mPlayingState == STOPPED) { 1327 mPlayingState = RUNNING; 1328 if (mSeekFraction < 0) { 1329 mStartTime = frameTime; 1330 } else { 1331 long seekTime = (long) (mDuration * mSeekFraction); 1332 mStartTime = frameTime - seekTime; 1333 mSeekFraction = -1; 1334 } 1335 } 1336 if (mPaused) { 1337 if (mPauseTime < 0) { 1338 mPauseTime = frameTime; 1339 } 1340 return false; 1341 } else if (mResumed) { 1342 mResumed = false; 1343 if (mPauseTime > 0) { 1344 // Offset by the duration that the animation was paused 1345 mStartTime += (frameTime - mPauseTime); 1346 } 1347 } 1348 // The frame time might be before the start time during the first frame of 1349 // an animation. The "current time" must always be on or after the start 1350 // time to avoid animating frames at negative time intervals. In practice, this 1351 // is very rare and only happens when seeking backwards. 1352 final long currentTime = Math.max(frameTime, mStartTime); 1353 return animationFrame(currentTime); 1354 } 1355 1356 /** 1357 * Returns the current animation fraction, which is the elapsed/interpolated fraction used in 1358 * the most recent frame update on the animation. 1359 * 1360 * @return Elapsed/interpolated fraction of the animation. 1361 */ 1362 public float getAnimatedFraction() { 1363 return mCurrentFraction; 1364 } 1365 1366 /** 1367 * This method is called with the elapsed fraction of the animation during every 1368 * animation frame. This function turns the elapsed fraction into an interpolated fraction 1369 * and then into an animated value (from the evaluator. The function is called mostly during 1370 * animation updates, but it is also called when the <code>end()</code> 1371 * function is called, to set the final value on the property. 1372 * 1373 * <p>Overrides of this method must call the superclass to perform the calculation 1374 * of the animated value.</p> 1375 * 1376 * @param fraction The elapsed fraction of the animation. 1377 */ 1378 void animateValue(float fraction) { 1379 fraction = mInterpolator.getInterpolation(fraction); 1380 mCurrentFraction = fraction; 1381 int numValues = mValues.length; 1382 for (int i = 0; i < numValues; ++i) { 1383 mValues[i].calculateValue(fraction); 1384 } 1385 if (mUpdateListeners != null) { 1386 int numListeners = mUpdateListeners.size(); 1387 for (int i = 0; i < numListeners; ++i) { 1388 mUpdateListeners.get(i).onAnimationUpdate(this); 1389 } 1390 } 1391 } 1392 1393 @Override 1394 public ValueAnimator clone() { 1395 final ValueAnimator anim = (ValueAnimator) super.clone(); 1396 if (mUpdateListeners != null) { 1397 anim.mUpdateListeners = new ArrayList<AnimatorUpdateListener>(mUpdateListeners); 1398 } 1399 anim.mSeekFraction = -1; 1400 anim.mPlayingBackwards = false; 1401 anim.mReversing = false; 1402 anim.mCurrentIteration = 0; 1403 anim.mInitialized = false; 1404 anim.mPlayingState = STOPPED; 1405 anim.mStartedDelay = false; 1406 PropertyValuesHolder[] oldValues = mValues; 1407 if (oldValues != null) { 1408 int numValues = oldValues.length; 1409 anim.mValues = new PropertyValuesHolder[numValues]; 1410 anim.mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues); 1411 for (int i = 0; i < numValues; ++i) { 1412 PropertyValuesHolder newValuesHolder = oldValues[i].clone(); 1413 anim.mValues[i] = newValuesHolder; 1414 anim.mValuesMap.put(newValuesHolder.getPropertyName(), newValuesHolder); 1415 } 1416 } 1417 return anim; 1418 } 1419 1420 /** 1421 * Implementors of this interface can add themselves as update listeners 1422 * to an <code>ValueAnimator</code> instance to receive callbacks on every animation 1423 * frame, after the current frame's values have been calculated for that 1424 * <code>ValueAnimator</code>. 1425 */ 1426 public static interface AnimatorUpdateListener { 1427 /** 1428 * <p>Notifies the occurrence of another frame of the animation.</p> 1429 * 1430 * @param animation The animation which was repeated. 1431 */ 1432 void onAnimationUpdate(ValueAnimator animation); 1433 1434 } 1435 1436 /** 1437 * Return the number of animations currently running. 1438 * 1439 * Used by StrictMode internally to annotate violations. 1440 * May be called on arbitrary threads! 1441 * 1442 * @hide 1443 */ 1444 public static int getCurrentAnimationsCount() { 1445 AnimationHandler handler = sAnimationHandler.get(); 1446 return handler != null ? handler.mAnimations.size() : 0; 1447 } 1448 1449 /** 1450 * Clear all animations on this thread, without canceling or ending them. 1451 * This should be used with caution. 1452 * 1453 * @hide 1454 */ 1455 public static void clearAllAnimations() { 1456 AnimationHandler handler = sAnimationHandler.get(); 1457 if (handler != null) { 1458 handler.mAnimations.clear(); 1459 handler.mPendingAnimations.clear(); 1460 handler.mDelayedAnims.clear(); 1461 } 1462 } 1463 1464 private static AnimationHandler getOrCreateAnimationHandler() { 1465 AnimationHandler handler = sAnimationHandler.get(); 1466 if (handler == null) { 1467 handler = new AnimationHandler(); 1468 sAnimationHandler.set(handler); 1469 } 1470 return handler; 1471 } 1472 1473 @Override 1474 public String toString() { 1475 String returnVal = "ValueAnimator@" + Integer.toHexString(hashCode()); 1476 if (mValues != null) { 1477 for (int i = 0; i < mValues.length; ++i) { 1478 returnVal += "\n " + mValues[i].toString(); 1479 } 1480 } 1481 return returnVal; 1482 } 1483 1484 /** 1485 * <p>Whether or not the ValueAnimator is allowed to run asynchronously off of 1486 * the UI thread. This is a hint that informs the ValueAnimator that it is 1487 * OK to run the animation off-thread, however ValueAnimator may decide 1488 * that it must run the animation on the UI thread anyway. For example if there 1489 * is an {@link AnimatorUpdateListener} the animation will run on the UI thread, 1490 * regardless of the value of this hint.</p> 1491 * 1492 * <p>Regardless of whether or not the animation runs asynchronously, all 1493 * listener callbacks will be called on the UI thread.</p> 1494 * 1495 * <p>To be able to use this hint the following must be true:</p> 1496 * <ol> 1497 * <li>{@link #getAnimatedFraction()} is not needed (it will return undefined values).</li> 1498 * <li>The animator is immutable while {@link #isStarted()} is true. Requests 1499 * to change values, duration, delay, etc... may be ignored.</li> 1500 * <li>Lifecycle callback events may be asynchronous. Events such as 1501 * {@link Animator.AnimatorListener#onAnimationEnd(Animator)} or 1502 * {@link Animator.AnimatorListener#onAnimationRepeat(Animator)} may end up delayed 1503 * as they must be posted back to the UI thread, and any actions performed 1504 * by those callbacks (such as starting new animations) will not happen 1505 * in the same frame.</li> 1506 * <li>State change requests ({@link #cancel()}, {@link #end()}, {@link #reverse()}, etc...) 1507 * may be asynchronous. It is guaranteed that all state changes that are 1508 * performed on the UI thread in the same frame will be applied as a single 1509 * atomic update, however that frame may be the current frame, 1510 * the next frame, or some future frame. This will also impact the observed 1511 * state of the Animator. For example, {@link #isStarted()} may still return true 1512 * after a call to {@link #end()}. Using the lifecycle callbacks is preferred over 1513 * queries to {@link #isStarted()}, {@link #isRunning()}, and {@link #isPaused()} 1514 * for this reason.</li> 1515 * </ol> 1516 * @hide 1517 */ 1518 @Override 1519 public void setAllowRunningAsynchronously(boolean mayRunAsync) { 1520 // It is up to subclasses to support this, if they can. 1521 } 1522} 1523