2 * Copyright (C) 2010 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com
.actionbarsherlock
.internal
.nineoldandroids
.animation
;
19 import android
.os
.Handler
;
20 import android
.os
.Looper
;
21 import android
.os
.Message
;
22 import android
.util
.AndroidRuntimeException
;
23 import android
.view
.animation
.AccelerateDecelerateInterpolator
;
24 import android
.view
.animation
.AnimationUtils
;
25 import android
.view
.animation
.Interpolator
;
26 import android
.view
.animation
.LinearInterpolator
;
28 import java
.util
.ArrayList
;
29 import java
.util
.HashMap
;
32 * This class provides a simple timing engine for running animations
33 * which calculate animated values and set them on target objects.
35 * <p>There is a single timing pulse that all animations use. It runs in a
36 * custom handler to ensure that property changes happen on the UI thread.</p>
38 * <p>By default, ValueAnimator uses non-linear time interpolation, via the
39 * {@link AccelerateDecelerateInterpolator} class, which accelerates into and decelerates
40 * out of an animation. This behavior can be changed by calling
41 * {@link ValueAnimator#setInterpolator(TimeInterpolator)}.</p>
43 @SuppressWarnings({"rawtypes", "unchecked"})
44 public class ValueAnimator
extends Animator
{
51 * The default amount of time in ms between animation frames
53 private static final long DEFAULT_FRAME_DELAY
= 10;
56 * Messages sent to timing handler: START is sent when an animation first begins, FRAME is sent
57 * by the handler to itself to process the next animation frame
59 static final int ANIMATION_START
= 0;
60 static final int ANIMATION_FRAME
= 1;
63 * Values used with internal variable mPlayingState to indicate the current state of an
66 static final int STOPPED
= 0; // Not yet playing
67 static final int RUNNING
= 1; // Playing normally
68 static final int SEEKED
= 2; // Seeked to some time value
72 * NOTE: This object implements the clone() method, making a deep copy of any referenced
73 * objects. As other non-trivial fields are added to this class, make sure to add logic
74 * to clone() to make deep copies of them.
77 // The first time that the animation's animateFrame() method is called. This time is used to
78 // determine elapsed time (and therefore the elapsed fraction) in subsequent calls
83 * Set when setCurrentPlayTime() is called. If negative, animation is not currently seeked
88 // TODO: We access the following ThreadLocal variables often, some of them on every update.
89 // If ThreadLocal access is significantly expensive, we may want to put all of these
90 // fields into a structure sot hat we just access ThreadLocal once to get the reference
91 // to that structure, then access the structure directly for each field.
93 // The static sAnimationHandler processes the internal timing loop on which all animations
95 private static ThreadLocal
<AnimationHandler
> sAnimationHandler
=
96 new ThreadLocal
<AnimationHandler
>();
98 // The per-thread list of all active animations
99 private static final ThreadLocal
<ArrayList
<ValueAnimator
>> sAnimations
=
100 new ThreadLocal
<ArrayList
<ValueAnimator
>>() {
102 protected ArrayList
<ValueAnimator
> initialValue() {
103 return new ArrayList
<ValueAnimator
>();
107 // The per-thread set of animations to be started on the next animation frame
108 private static final ThreadLocal
<ArrayList
<ValueAnimator
>> sPendingAnimations
=
109 new ThreadLocal
<ArrayList
<ValueAnimator
>>() {
111 protected ArrayList
<ValueAnimator
> initialValue() {
112 return new ArrayList
<ValueAnimator
>();
117 * Internal per-thread collections used to avoid set collisions as animations start and end
118 * while being processed.
120 private static final ThreadLocal
<ArrayList
<ValueAnimator
>> sDelayedAnims
=
121 new ThreadLocal
<ArrayList
<ValueAnimator
>>() {
123 protected ArrayList
<ValueAnimator
> initialValue() {
124 return new ArrayList
<ValueAnimator
>();
128 private static final ThreadLocal
<ArrayList
<ValueAnimator
>> sEndingAnims
=
129 new ThreadLocal
<ArrayList
<ValueAnimator
>>() {
131 protected ArrayList
<ValueAnimator
> initialValue() {
132 return new ArrayList
<ValueAnimator
>();
136 private static final ThreadLocal
<ArrayList
<ValueAnimator
>> sReadyAnims
=
137 new ThreadLocal
<ArrayList
<ValueAnimator
>>() {
139 protected ArrayList
<ValueAnimator
> initialValue() {
140 return new ArrayList
<ValueAnimator
>();
144 // The time interpolator to be used if none is set on the animation
145 private static final /*Time*/Interpolator sDefaultInterpolator
=
146 new AccelerateDecelerateInterpolator();
148 // type evaluators for the primitive types handled by this implementation
149 //private static final TypeEvaluator sIntEvaluator = new IntEvaluator();
150 //private static final TypeEvaluator sFloatEvaluator = new FloatEvaluator();
153 * Used to indicate whether the animation is currently playing in reverse. This causes the
154 * elapsed fraction to be inverted to calculate the appropriate values.
156 private boolean mPlayingBackwards
= false
;
159 * This variable tracks the current iteration that is playing. When mCurrentIteration exceeds the
160 * repeatCount (if repeatCount!=INFINITE), the animation ends
162 private int mCurrentIteration
= 0;
165 * Tracks current elapsed/eased fraction, for querying in getAnimatedFraction().
167 private float mCurrentFraction
= 0f
;
170 * Tracks whether a startDelay'd animation has begun playing through the startDelay.
172 private boolean mStartedDelay
= false
;
175 * Tracks the time at which the animation began playing through its startDelay. This is
176 * different from the mStartTime variable, which is used to track when the animation became
177 * active (which is when the startDelay expired and the animation was added to the active
180 private long mDelayStartTime
;
183 * Flag that represents the current state of the animation. Used to figure out when to start
184 * an animation (if state == STOPPED). Also used to end an animation that
185 * has been cancel()'d or end()'d since the last animation frame. Possible values are
186 * STOPPED, RUNNING, SEEKED.
188 int mPlayingState
= STOPPED
;
191 * Additional playing state to indicate whether an animator has been start()'d. There is
192 * some lag between a call to start() and the first animation frame. We should still note
193 * that the animation has been started, even if it's first animation frame has not yet
194 * happened, and reflect that state in isRunning().
195 * Note that delayed animations are different: they are not started until their first
196 * animation frame, which occurs after their delay elapses.
198 private boolean mRunning
= false
;
201 * Additional playing state to indicate whether an animator has been start()'d, whether or
202 * not there is a nonzero startDelay.
204 private boolean mStarted
= false
;
207 * Flag that denotes whether the animation is set up and ready to go. Used to
208 * set up animation that has not yet been started.
210 boolean mInitialized
= false
;
216 // How long the animation should last in ms
217 private long mDuration
= 300;
219 // The amount of time in ms to delay starting the animation after start() is called
220 private long mStartDelay
= 0;
222 // The number of milliseconds between animation frames
223 private static long sFrameDelay
= DEFAULT_FRAME_DELAY
;
225 // The number of times the animation will repeat. The default is 0, which means the animation
226 // will play only once
227 private int mRepeatCount
= 0;
230 * The type of repetition that will occur when repeatMode is nonzero. RESTART means the
231 * animation will start from the beginning on every new cycle. REVERSE means the animation
232 * will reverse directions on each iteration.
234 private int mRepeatMode
= RESTART
;
237 * The time interpolator to be used. The elapsed fraction of the animation will be passed
238 * through this interpolator to calculate the interpolated fraction, which is then used to
239 * calculate the animated values.
241 private /*Time*/Interpolator mInterpolator
= sDefaultInterpolator
;
244 * The set of listeners to be sent events through the life of an animation.
246 private ArrayList
<AnimatorUpdateListener
> mUpdateListeners
= null
;
249 * The property/value sets being animated.
251 PropertyValuesHolder
[] mValues
;
254 * A hashmap of the PropertyValuesHolder objects. This map is used to lookup animated values
255 * by property name during calls to getAnimatedValue(String).
257 HashMap
<String
, PropertyValuesHolder
> mValuesMap
;
264 * When the animation reaches the end and <code>repeatCount</code> is INFINITE
265 * or a positive value, the animation restarts from the beginning.
267 public static final int RESTART
= 1;
269 * When the animation reaches the end and <code>repeatCount</code> is INFINITE
270 * or a positive value, the animation reverses direction on every iteration.
272 public static final int REVERSE
= 2;
274 * This value used used with the {@link #setRepeatCount(int)} property to repeat
275 * the animation indefinitely.
277 public static final int INFINITE
= -1;
280 * Creates a new ValueAnimator object. This default constructor is primarily for
281 * use internally; the factory methods which take parameters are more generally
284 public ValueAnimator() {
288 * Constructs and returns a ValueAnimator that animates between int values. A single
289 * value implies that that value is the one being animated to. However, this is not typically
290 * useful in a ValueAnimator object because there is no way for the object to determine the
291 * starting value for the animation (unlike ObjectAnimator, which can derive that value
292 * from the target object and property being animated). Therefore, there should typically
293 * be two or more values.
295 * @param values A set of values that the animation will animate between over time.
296 * @return A ValueAnimator object that is set up to animate between the given values.
298 public static ValueAnimator
ofInt(int... values
) {
299 ValueAnimator anim
= new ValueAnimator();
300 anim
.setIntValues(values
);
305 * Constructs and returns a ValueAnimator that animates between float values. A single
306 * value implies that that value is the one being animated to. However, this is not typically
307 * useful in a ValueAnimator object because there is no way for the object to determine the
308 * starting value for the animation (unlike ObjectAnimator, which can derive that value
309 * from the target object and property being animated). Therefore, there should typically
310 * be two or more values.
312 * @param values A set of values that the animation will animate between over time.
313 * @return A ValueAnimator object that is set up to animate between the given values.
315 public static ValueAnimator
ofFloat(float... values
) {
316 ValueAnimator anim
= new ValueAnimator();
317 anim
.setFloatValues(values
);
322 * Constructs and returns a ValueAnimator that animates between the values
323 * specified in the PropertyValuesHolder objects.
325 * @param values A set of PropertyValuesHolder objects whose values will be animated
327 * @return A ValueAnimator object that is set up to animate between the given values.
329 public static ValueAnimator
ofPropertyValuesHolder(PropertyValuesHolder
... values
) {
330 ValueAnimator anim
= new ValueAnimator();
331 anim
.setValues(values
);
335 * Constructs and returns a ValueAnimator that animates between Object values. A single
336 * value implies that that value is the one being animated to. However, this is not typically
337 * useful in a ValueAnimator object because there is no way for the object to determine the
338 * starting value for the animation (unlike ObjectAnimator, which can derive that value
339 * from the target object and property being animated). Therefore, there should typically
340 * be two or more values.
342 * <p>Since ValueAnimator does not know how to animate between arbitrary Objects, this
343 * factory method also takes a TypeEvaluator object that the ValueAnimator will use
344 * to perform that interpolation.
346 * @param evaluator A TypeEvaluator that will be called on each animation frame to
347 * provide the ncessry interpolation between the Object values to derive the animated
349 * @param values A set of values that the animation will animate between over time.
350 * @return A ValueAnimator object that is set up to animate between the given values.
352 public static ValueAnimator
ofObject(TypeEvaluator evaluator
, Object
... values
) {
353 ValueAnimator anim
= new ValueAnimator();
354 anim
.setObjectValues(values
);
355 anim
.setEvaluator(evaluator
);
360 * Sets int values that will be animated between. A single
361 * value implies that that value is the one being animated to. However, this is not typically
362 * useful in a ValueAnimator object because there is no way for the object to determine the
363 * starting value for the animation (unlike ObjectAnimator, which can derive that value
364 * from the target object and property being animated). Therefore, there should typically
365 * be two or more values.
367 * <p>If there are already multiple sets of values defined for this ValueAnimator via more
368 * than one PropertyValuesHolder object, this method will set the values for the first
369 * of those objects.</p>
371 * @param values A set of values that the animation will animate between over time.
373 public void setIntValues(int... values
) {
374 if (values
== null
|| values
.length
== 0) {
377 if (mValues
== null
|| mValues
.length
== 0) {
378 setValues(new PropertyValuesHolder
[]{PropertyValuesHolder
.ofInt("", values
)});
380 PropertyValuesHolder valuesHolder
= mValues
[0];
381 valuesHolder
.setIntValues(values
);
383 // New property/values/target should cause re-initialization prior to starting
384 mInitialized
= false
;
388 * Sets float values that will be animated between. A single
389 * value implies that that value is the one being animated to. However, this is not typically
390 * useful in a ValueAnimator object because there is no way for the object to determine the
391 * starting value for the animation (unlike ObjectAnimator, which can derive that value
392 * from the target object and property being animated). Therefore, there should typically
393 * be two or more values.
395 * <p>If there are already multiple sets of values defined for this ValueAnimator via more
396 * than one PropertyValuesHolder object, this method will set the values for the first
397 * of those objects.</p>
399 * @param values A set of values that the animation will animate between over time.
401 public void setFloatValues(float... values
) {
402 if (values
== null
|| values
.length
== 0) {
405 if (mValues
== null
|| mValues
.length
== 0) {
406 setValues(new PropertyValuesHolder
[]{PropertyValuesHolder
.ofFloat("", values
)});
408 PropertyValuesHolder valuesHolder
= mValues
[0];
409 valuesHolder
.setFloatValues(values
);
411 // New property/values/target should cause re-initialization prior to starting
412 mInitialized
= false
;
416 * Sets the values to animate between for this animation. A single
417 * value implies that that value is the one being animated to. However, this is not typically
418 * useful in a ValueAnimator object because there is no way for the object to determine the
419 * starting value for the animation (unlike ObjectAnimator, which can derive that value
420 * from the target object and property being animated). Therefore, there should typically
421 * be two or more values.
423 * <p>If there are already multiple sets of values defined for this ValueAnimator via more
424 * than one PropertyValuesHolder object, this method will set the values for the first
425 * of those objects.</p>
427 * <p>There should be a TypeEvaluator set on the ValueAnimator that knows how to interpolate
428 * between these value objects. ValueAnimator only knows how to interpolate between the
429 * primitive types specified in the other setValues() methods.</p>
431 * @param values The set of values to animate between.
433 public void setObjectValues(Object
... values
) {
434 if (values
== null
|| values
.length
== 0) {
437 if (mValues
== null
|| mValues
.length
== 0) {
438 setValues(new PropertyValuesHolder
[]{PropertyValuesHolder
.ofObject("",
439 (TypeEvaluator
)null
, values
)});
441 PropertyValuesHolder valuesHolder
= mValues
[0];
442 valuesHolder
.setObjectValues(values
);
444 // New property/values/target should cause re-initialization prior to starting
445 mInitialized
= false
;
449 * Sets the values, per property, being animated between. This function is called internally
450 * by the constructors of ValueAnimator that take a list of values. But an ValueAnimator can
451 * be constructed without values and this method can be called to set the values manually
454 * @param values The set of values, per property, being animated between.
456 public void setValues(PropertyValuesHolder
... values
) {
457 int numValues
= values
.length
;
459 mValuesMap
= new HashMap
<String
, PropertyValuesHolder
>(numValues
);
460 for (int i
= 0; i
< numValues
; ++i
) {
461 PropertyValuesHolder valuesHolder
= values
[i
];
462 mValuesMap
.put(valuesHolder
.getPropertyName(), valuesHolder
);
464 // New property/values/target should cause re-initialization prior to starting
465 mInitialized
= false
;
469 * Returns the values that this ValueAnimator animates between. These values are stored in
470 * PropertyValuesHolder objects, even if the ValueAnimator was created with a simple list
471 * of value objects instead.
473 * @return PropertyValuesHolder[] An array of PropertyValuesHolder objects which hold the
474 * values, per property, that define the animation.
476 public PropertyValuesHolder
[] getValues() {
481 * This function is called immediately before processing the first animation
482 * frame of an animation. If there is a nonzero <code>startDelay</code>, the
483 * function is called after that delay ends.
484 * It takes care of the final initialization steps for the
487 * <p>Overrides of this method should call the superclass method to ensure
488 * that internal mechanisms for the animation are set up correctly.</p>
490 void initAnimation() {
492 int numValues
= mValues
.length
;
493 for (int i
= 0; i
< numValues
; ++i
) {
502 * Sets the length of the animation. The default duration is 300 milliseconds.
504 * @param duration The length of the animation, in milliseconds. This value cannot
506 * @return ValueAnimator The object called with setDuration(). This return
507 * value makes it easier to compose statements together that construct and then set the
508 * duration, as in <code>ValueAnimator.ofInt(0, 10).setDuration(500).start()</code>.
510 public ValueAnimator
setDuration(long duration
) {
512 throw new IllegalArgumentException("Animators cannot have negative duration: " +
515 mDuration
= duration
;
520 * Gets the length of the animation. The default duration is 300 milliseconds.
522 * @return The length of the animation, in milliseconds.
524 public long getDuration() {
529 * Sets the position of the animation to the specified point in time. This time should
530 * be between 0 and the total duration of the animation, including any repetition. If
531 * the animation has not yet been started, then it will not advance forward after it is
532 * set to this time; it will simply set the time to this value and perform any appropriate
533 * actions based on that time. If the animation is already running, then setCurrentPlayTime()
534 * will set the current playing time to this value and continue playing from that point.
536 * @param playTime The time, in milliseconds, to which the animation is advanced or rewound.
538 public void setCurrentPlayTime(long playTime
) {
540 long currentTime
= AnimationUtils
.currentAnimationTimeMillis();
541 if (mPlayingState
!= RUNNING
) {
542 mSeekTime
= playTime
;
543 mPlayingState
= SEEKED
;
545 mStartTime
= currentTime
- playTime
;
546 animationFrame(currentTime
);
550 * Gets the current position of the animation in time, which is equal to the current
551 * time minus the time that the animation started. An animation that is not yet started will
552 * return a value of zero.
554 * @return The current position in time of the animation.
556 public long getCurrentPlayTime() {
557 if (!mInitialized
|| mPlayingState
== STOPPED
) {
560 return AnimationUtils
.currentAnimationTimeMillis() - mStartTime
;
564 * This custom, static handler handles the timing pulse that is shared by
565 * all active animations. This approach ensures that the setting of animation
566 * values will happen on the UI thread and that all animations will share
567 * the same times for calculating their values, which makes synchronizing
568 * animations possible.
571 private static class AnimationHandler
extends Handler
{
573 * There are only two messages that we care about: ANIMATION_START and
574 * ANIMATION_FRAME. The START message is sent when an animation's start()
575 * method is called. It cannot start synchronously when start() is called
576 * because the call may be on the wrong thread, and it would also not be
577 * synchronized with other animations because it would not start on a common
578 * timing pulse. So each animation sends a START message to the handler, which
579 * causes the handler to place the animation on the active animations queue and
580 * start processing frames for that animation.
581 * The FRAME message is the one that is sent over and over while there are any
582 * active animations to process.
585 public void handleMessage(Message msg
) {
586 boolean callAgain
= true
;
587 ArrayList
<ValueAnimator
> animations
= sAnimations
.get();
588 ArrayList
<ValueAnimator
> delayedAnims
= sDelayedAnims
.get();
590 // TODO: should we avoid sending frame message when starting if we
591 // were already running?
592 case ANIMATION_START
:
593 ArrayList
<ValueAnimator
> pendingAnimations
= sPendingAnimations
.get();
594 if (animations
.size() > 0 || delayedAnims
.size() > 0) {
597 // pendingAnims holds any animations that have requested to be started
598 // We're going to clear sPendingAnimations, but starting animation may
599 // cause more to be added to the pending list (for example, if one animation
600 // starting triggers another starting). So we loop until sPendingAnimations
602 while (pendingAnimations
.size() > 0) {
603 ArrayList
<ValueAnimator
> pendingCopy
=
604 (ArrayList
<ValueAnimator
>) pendingAnimations
.clone();
605 pendingAnimations
.clear();
606 int count
= pendingCopy
.size();
607 for (int i
= 0; i
< count
; ++i
) {
608 ValueAnimator anim
= pendingCopy
.get(i
);
609 // If the animation has a startDelay, place it on the delayed list
610 if (anim
.mStartDelay
== 0) {
611 anim
.startAnimation();
613 delayedAnims
.add(anim
);
617 // fall through to process first frame of new animations
618 case ANIMATION_FRAME
:
619 // currentTime holds the common time for all animations processed
621 long currentTime
= AnimationUtils
.currentAnimationTimeMillis();
622 ArrayList
<ValueAnimator
> readyAnims
= sReadyAnims
.get();
623 ArrayList
<ValueAnimator
> endingAnims
= sEndingAnims
.get();
625 // First, process animations currently sitting on the delayed queue, adding
626 // them to the active animations if they are ready
627 int numDelayedAnims
= delayedAnims
.size();
628 for (int i
= 0; i
< numDelayedAnims
; ++i
) {
629 ValueAnimator anim
= delayedAnims
.get(i
);
630 if (anim
.delayedAnimationFrame(currentTime
)) {
631 readyAnims
.add(anim
);
634 int numReadyAnims
= readyAnims
.size();
635 if (numReadyAnims
> 0) {
636 for (int i
= 0; i
< numReadyAnims
; ++i
) {
637 ValueAnimator anim
= readyAnims
.get(i
);
638 anim
.startAnimation();
639 anim
.mRunning
= true
;
640 delayedAnims
.remove(anim
);
645 // Now process all active animations. The return value from animationFrame()
646 // tells the handler whether it should now be ended
647 int numAnims
= animations
.size();
649 while (i
< numAnims
) {
650 ValueAnimator anim
= animations
.get(i
);
651 if (anim
.animationFrame(currentTime
)) {
652 endingAnims
.add(anim
);
654 if (animations
.size() == numAnims
) {
657 // An animation might be canceled or ended by client code
658 // during the animation frame. Check to see if this happened by
659 // seeing whether the current index is the same as it was before
660 // calling animationFrame(). Another approach would be to copy
661 // animations to a temporary list and process that list instead,
662 // but that entails garbage and processing overhead that would
665 endingAnims
.remove(anim
);
668 if (endingAnims
.size() > 0) {
669 for (i
= 0; i
< endingAnims
.size(); ++i
) {
670 endingAnims
.get(i
).endAnimation();
675 // If there are still active or delayed animations, call the handler again
676 // after the frameDelay
677 if (callAgain
&& (!animations
.isEmpty() || !delayedAnims
.isEmpty())) {
678 sendEmptyMessageDelayed(ANIMATION_FRAME
, Math
.max(0, sFrameDelay
-
679 (AnimationUtils
.currentAnimationTimeMillis() - currentTime
)));
687 * The amount of time, in milliseconds, to delay starting the animation after
688 * {@link #start()} is called.
690 * @return the number of milliseconds to delay running the animation
692 public long getStartDelay() {
697 * The amount of time, in milliseconds, to delay starting the animation after
698 * {@link #start()} is called.
700 * @param startDelay The amount of the delay, in milliseconds
702 public void setStartDelay(long startDelay
) {
703 this.mStartDelay
= startDelay
;
707 * The amount of time, in milliseconds, between each frame of the animation. This is a
708 * requested time that the animation will attempt to honor, but the actual delay between
709 * frames may be different, depending on system load and capabilities. This is a static
710 * function because the same delay will be applied to all animations, since they are all
711 * run off of a single timing loop.
713 * @return the requested time between frames, in milliseconds
715 public static long getFrameDelay() {
720 * The amount of time, in milliseconds, between each frame of the animation. This is a
721 * requested time that the animation will attempt to honor, but the actual delay between
722 * frames may be different, depending on system load and capabilities. This is a static
723 * function because the same delay will be applied to all animations, since they are all
724 * run off of a single timing loop.
726 * @param frameDelay the requested time between frames, in milliseconds
728 public static void setFrameDelay(long frameDelay
) {
729 sFrameDelay
= frameDelay
;
733 * The most recent value calculated by this <code>ValueAnimator</code> when there is just one
734 * property being animated. This value is only sensible while the animation is running. The main
735 * purpose for this read-only property is to retrieve the value from the <code>ValueAnimator</code>
736 * during a call to {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
737 * is called during each animation frame, immediately after the value is calculated.
739 * @return animatedValue The value most recently calculated by this <code>ValueAnimator</code> for
740 * the single property being animated. If there are several properties being animated
741 * (specified by several PropertyValuesHolder objects in the constructor), this function
742 * returns the animated value for the first of those objects.
744 public Object
getAnimatedValue() {
745 if (mValues
!= null
&& mValues
.length
> 0) {
746 return mValues
[0].getAnimatedValue();
748 // Shouldn't get here; should always have values unless ValueAnimator was set up wrong
753 * The most recent value calculated by this <code>ValueAnimator</code> for <code>propertyName</code>.
754 * The main purpose for this read-only property is to retrieve the value from the
755 * <code>ValueAnimator</code> during a call to
756 * {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
757 * is called during each animation frame, immediately after the value is calculated.
759 * @return animatedValue The value most recently calculated for the named property
760 * by this <code>ValueAnimator</code>.
762 public Object
getAnimatedValue(String propertyName
) {
763 PropertyValuesHolder valuesHolder
= mValuesMap
.get(propertyName
);
764 if (valuesHolder
!= null
) {
765 return valuesHolder
.getAnimatedValue();
767 // At least avoid crashing if called with bogus propertyName
773 * Sets how many times the animation should be repeated. If the repeat
774 * count is 0, the animation is never repeated. If the repeat count is
775 * greater than 0 or {@link #INFINITE}, the repeat mode will be taken
776 * into account. The repeat count is 0 by default.
778 * @param value the number of times the animation should be repeated
780 public void setRepeatCount(int value
) {
781 mRepeatCount
= value
;
784 * Defines how many times the animation should repeat. The default value
787 * @return the number of times the animation should repeat, or {@link #INFINITE}
789 public int getRepeatCount() {
794 * Defines what this animation should do when it reaches the end. This
795 * setting is applied only when the repeat count is either greater than
796 * 0 or {@link #INFINITE}. Defaults to {@link #RESTART}.
798 * @param value {@link #RESTART} or {@link #REVERSE}
800 public void setRepeatMode(int value
) {
805 * Defines what this animation should do when it reaches the end.
807 * @return either one of {@link #REVERSE} or {@link #RESTART}
809 public int getRepeatMode() {
814 * Adds a listener to the set of listeners that are sent update events through the life of
815 * an animation. This method is called on all listeners for every frame of the animation,
816 * after the values for the animation have been calculated.
818 * @param listener the listener to be added to the current set of listeners for this animation.
820 public void addUpdateListener(AnimatorUpdateListener listener
) {
821 if (mUpdateListeners
== null
) {
822 mUpdateListeners
= new ArrayList
<AnimatorUpdateListener
>();
824 mUpdateListeners
.add(listener
);
828 * Removes all listeners from the set listening to frame updates for this animation.
830 public void removeAllUpdateListeners() {
831 if (mUpdateListeners
== null
) {
834 mUpdateListeners
.clear();
835 mUpdateListeners
= null
;
839 * Removes a listener from the set listening to frame updates for this animation.
841 * @param listener the listener to be removed from the current set of update listeners
842 * for this animation.
844 public void removeUpdateListener(AnimatorUpdateListener listener
) {
845 if (mUpdateListeners
== null
) {
848 mUpdateListeners
.remove(listener
);
849 if (mUpdateListeners
.size() == 0) {
850 mUpdateListeners
= null
;
856 * The time interpolator used in calculating the elapsed fraction of this animation. The
857 * interpolator determines whether the animation runs with linear or non-linear motion,
858 * such as acceleration and deceleration. The default value is
859 * {@link android.view.animation.AccelerateDecelerateInterpolator}
861 * @param value the interpolator to be used by this animation. A value of <code>null</code>
862 * will result in linear interpolation.
865 public void setInterpolator(/*Time*/Interpolator value
) {
867 mInterpolator
= value
;
869 mInterpolator
= new LinearInterpolator();
874 * Returns the timing interpolator that this ValueAnimator uses.
876 * @return The timing interpolator for this ValueAnimator.
878 public /*Time*/Interpolator
getInterpolator() {
879 return mInterpolator
;
883 * The type evaluator to be used when calculating the animated values of this animation.
884 * The system will automatically assign a float or int evaluator based on the type
885 * of <code>startValue</code> and <code>endValue</code> in the constructor. But if these values
886 * are not one of these primitive types, or if different evaluation is desired (such as is
887 * necessary with int values that represent colors), a custom evaluator needs to be assigned.
888 * For example, when running an animation on color values, the {@link ArgbEvaluator}
889 * should be used to get correct RGB color interpolation.
891 * <p>If this ValueAnimator has only one set of values being animated between, this evaluator
892 * will be used for that set. If there are several sets of values being animated, which is
893 * the case if PropertyValuesHOlder objects were set on the ValueAnimator, then the evaluator
894 * is assigned just to the first PropertyValuesHolder object.</p>
896 * @param value the evaluator to be used this animation
898 public void setEvaluator(TypeEvaluator value
) {
899 if (value
!= null
&& mValues
!= null
&& mValues
.length
> 0) {
900 mValues
[0].setEvaluator(value
);
905 * Start the animation playing. This version of start() takes a boolean flag that indicates
906 * whether the animation should play in reverse. The flag is usually false, but may be set
907 * to true if called from the reverse() method.
909 * <p>The animation started by calling this method will be run on the thread that called
910 * this method. This thread should have a Looper on it (a runtime exception will be thrown if
911 * this is not the case). Also, if the animation will animate
912 * properties of objects in the view hierarchy, then the calling thread should be the UI
913 * thread for that view hierarchy.</p>
915 * @param playBackwards Whether the ValueAnimator should start playing in reverse.
917 private void start(boolean playBackwards
) {
918 if (Looper
.myLooper() == null
) {
919 throw new AndroidRuntimeException("Animators may only be run on Looper threads");
921 mPlayingBackwards
= playBackwards
;
922 mCurrentIteration
= 0;
923 mPlayingState
= STOPPED
;
925 mStartedDelay
= false
;
926 sPendingAnimations
.get().add(this);
927 if (mStartDelay
== 0) {
928 // This sets the initial value of the animation, prior to actually starting it running
929 setCurrentPlayTime(getCurrentPlayTime());
930 mPlayingState
= STOPPED
;
933 if (mListeners
!= null
) {
934 ArrayList
<AnimatorListener
> tmpListeners
=
935 (ArrayList
<AnimatorListener
>) mListeners
.clone();
936 int numListeners
= tmpListeners
.size();
937 for (int i
= 0; i
< numListeners
; ++i
) {
938 tmpListeners
.get(i
).onAnimationStart(this);
942 AnimationHandler animationHandler
= sAnimationHandler
.get();
943 if (animationHandler
== null
) {
944 animationHandler
= new AnimationHandler();
945 sAnimationHandler
.set(animationHandler
);
947 animationHandler
.sendEmptyMessage(ANIMATION_START
);
951 public void start() {
956 public void cancel() {
957 // Only cancel if the animation is actually running or has been started and is about
959 if (mPlayingState
!= STOPPED
|| sPendingAnimations
.get().contains(this) ||
960 sDelayedAnims
.get().contains(this)) {
961 // Only notify listeners if the animator has actually started
962 if (mRunning
&& mListeners
!= null
) {
963 ArrayList
<AnimatorListener
> tmpListeners
=
964 (ArrayList
<AnimatorListener
>) mListeners
.clone();
965 for (AnimatorListener listener
: tmpListeners
) {
966 listener
.onAnimationCancel(this);
975 if (!sAnimations
.get().contains(this) && !sPendingAnimations
.get().contains(this)) {
976 // Special case if the animation has not yet started; get it ready for ending
977 mStartedDelay
= false
;
979 } else if (!mInitialized
) {
982 // The final value set on the target varies, depending on whether the animation
983 // was supposed to repeat an odd number of times
984 if (mRepeatCount
> 0 && (mRepeatCount
& 0x01) == 1) {
993 public boolean isRunning() {
994 return (mPlayingState
== RUNNING
|| mRunning
);
998 public boolean isStarted() {
1003 * Plays the ValueAnimator in reverse. If the animation is already running,
1004 * it will stop itself and play backwards from the point reached when reverse was called.
1005 * If the animation is not currently running, then it will start from the end and
1006 * play backwards. This behavior is only set for the current animation; future playing
1007 * of the animation will use the default behavior of playing forward.
1009 public void reverse() {
1010 mPlayingBackwards
= !mPlayingBackwards
;
1011 if (mPlayingState
== RUNNING
) {
1012 long currentTime
= AnimationUtils
.currentAnimationTimeMillis();
1013 long currentPlayTime
= currentTime
- mStartTime
;
1014 long timeLeft
= mDuration
- currentPlayTime
;
1015 mStartTime
= currentTime
- timeLeft
;
1022 * Called internally to end an animation by removing it from the animations list. Must be
1023 * called on the UI thread.
1025 private void endAnimation() {
1026 sAnimations
.get().remove(this);
1027 sPendingAnimations
.get().remove(this);
1028 sDelayedAnims
.get().remove(this);
1029 mPlayingState
= STOPPED
;
1030 if (mRunning
&& mListeners
!= null
) {
1031 ArrayList
<AnimatorListener
> tmpListeners
=
1032 (ArrayList
<AnimatorListener
>) mListeners
.clone();
1033 int numListeners
= tmpListeners
.size();
1034 for (int i
= 0; i
< numListeners
; ++i
) {
1035 tmpListeners
.get(i
).onAnimationEnd(this);
1043 * Called internally to start an animation by adding it to the active animations list. Must be
1044 * called on the UI thread.
1046 private void startAnimation() {
1048 sAnimations
.get().add(this);
1049 if (mStartDelay
> 0 && mListeners
!= null
) {
1050 // Listeners were already notified in start() if startDelay is 0; this is
1051 // just for delayed animations
1052 ArrayList
<AnimatorListener
> tmpListeners
=
1053 (ArrayList
<AnimatorListener
>) mListeners
.clone();
1054 int numListeners
= tmpListeners
.size();
1055 for (int i
= 0; i
< numListeners
; ++i
) {
1056 tmpListeners
.get(i
).onAnimationStart(this);
1062 * Internal function called to process an animation frame on an animation that is currently
1063 * sleeping through its <code>startDelay</code> phase. The return value indicates whether it
1064 * should be woken up and put on the active animations queue.
1066 * @param currentTime The current animation time, used to calculate whether the animation
1067 * has exceeded its <code>startDelay</code> and should be started.
1068 * @return True if the animation's <code>startDelay</code> has been exceeded and the animation
1069 * should be added to the set of active animations.
1071 private boolean delayedAnimationFrame(long currentTime
) {
1072 if (!mStartedDelay
) {
1073 mStartedDelay
= true
;
1074 mDelayStartTime
= currentTime
;
1076 long deltaTime
= currentTime
- mDelayStartTime
;
1077 if (deltaTime
> mStartDelay
) {
1078 // startDelay ended - start the anim and record the
1079 // mStartTime appropriately
1080 mStartTime
= currentTime
- (deltaTime
- mStartDelay
);
1081 mPlayingState
= RUNNING
;
1089 * This internal function processes a single animation frame for a given animation. The
1090 * currentTime parameter is the timing pulse sent by the handler, used to calculate the
1091 * elapsed duration, and therefore
1092 * the elapsed fraction, of the animation. The return value indicates whether the animation
1093 * should be ended (which happens when the elapsed time of the animation exceeds the
1094 * animation's duration, including the repeatCount).
1096 * @param currentTime The current time, as tracked by the static timing handler
1097 * @return true if the animation's duration, including any repetitions due to
1098 * <code>repeatCount</code> has been exceeded and the animation should be ended.
1100 boolean animationFrame(long currentTime
) {
1101 boolean done
= false
;
1103 if (mPlayingState
== STOPPED
) {
1104 mPlayingState
= RUNNING
;
1105 if (mSeekTime
< 0) {
1106 mStartTime
= currentTime
;
1108 mStartTime
= currentTime
- mSeekTime
;
1109 // Now that we're playing, reset the seek time
1113 switch (mPlayingState
) {
1116 float fraction
= mDuration
> 0 ?
(float)(currentTime
- mStartTime
) / mDuration
: 1f
;
1117 if (fraction
>= 1f
) {
1118 if (mCurrentIteration
< mRepeatCount
|| mRepeatCount
== INFINITE
) {
1120 if (mListeners
!= null
) {
1121 int numListeners
= mListeners
.size();
1122 for (int i
= 0; i
< numListeners
; ++i
) {
1123 mListeners
.get(i
).onAnimationRepeat(this);
1126 if (mRepeatMode
== REVERSE
) {
1127 mPlayingBackwards
= mPlayingBackwards ? false
: true
;
1129 mCurrentIteration
+= (int)fraction
;
1130 fraction
= fraction
% 1f
;
1131 mStartTime
+= mDuration
;
1134 fraction
= Math
.min(fraction
, 1.0f
);
1137 if (mPlayingBackwards
) {
1138 fraction
= 1f
- fraction
;
1140 animateValue(fraction
);
1148 * Returns the current animation fraction, which is the elapsed/interpolated fraction used in
1149 * the most recent frame update on the animation.
1151 * @return Elapsed/interpolated fraction of the animation.
1153 public float getAnimatedFraction() {
1154 return mCurrentFraction
;
1158 * This method is called with the elapsed fraction of the animation during every
1159 * animation frame. This function turns the elapsed fraction into an interpolated fraction
1160 * and then into an animated value (from the evaluator. The function is called mostly during
1161 * animation updates, but it is also called when the <code>end()</code>
1162 * function is called, to set the final value on the property.
1164 * <p>Overrides of this method must call the superclass to perform the calculation
1165 * of the animated value.</p>
1167 * @param fraction The elapsed fraction of the animation.
1169 void animateValue(float fraction
) {
1170 fraction
= mInterpolator
.getInterpolation(fraction
);
1171 mCurrentFraction
= fraction
;
1172 int numValues
= mValues
.length
;
1173 for (int i
= 0; i
< numValues
; ++i
) {
1174 mValues
[i
].calculateValue(fraction
);
1176 if (mUpdateListeners
!= null
) {
1177 int numListeners
= mUpdateListeners
.size();
1178 for (int i
= 0; i
< numListeners
; ++i
) {
1179 mUpdateListeners
.get(i
).onAnimationUpdate(this);
1185 public ValueAnimator
clone() {
1186 final ValueAnimator anim
= (ValueAnimator
) super.clone();
1187 if (mUpdateListeners
!= null
) {
1188 ArrayList
<AnimatorUpdateListener
> oldListeners
= mUpdateListeners
;
1189 anim
.mUpdateListeners
= new ArrayList
<AnimatorUpdateListener
>();
1190 int numListeners
= oldListeners
.size();
1191 for (int i
= 0; i
< numListeners
; ++i
) {
1192 anim
.mUpdateListeners
.add(oldListeners
.get(i
));
1195 anim
.mSeekTime
= -1;
1196 anim
.mPlayingBackwards
= false
;
1197 anim
.mCurrentIteration
= 0;
1198 anim
.mInitialized
= false
;
1199 anim
.mPlayingState
= STOPPED
;
1200 anim
.mStartedDelay
= false
;
1201 PropertyValuesHolder
[] oldValues
= mValues
;
1202 if (oldValues
!= null
) {
1203 int numValues
= oldValues
.length
;
1204 anim
.mValues
= new PropertyValuesHolder
[numValues
];
1205 anim
.mValuesMap
= new HashMap
<String
, PropertyValuesHolder
>(numValues
);
1206 for (int i
= 0; i
< numValues
; ++i
) {
1207 PropertyValuesHolder newValuesHolder
= oldValues
[i
].clone();
1208 anim
.mValues
[i
] = newValuesHolder
;
1209 anim
.mValuesMap
.put(newValuesHolder
.getPropertyName(), newValuesHolder
);
1216 * Implementors of this interface can add themselves as update listeners
1217 * to an <code>ValueAnimator</code> instance to receive callbacks on every animation
1218 * frame, after the current frame's values have been calculated for that
1219 * <code>ValueAnimator</code>.
1221 public static interface AnimatorUpdateListener
{
1223 * <p>Notifies the occurrence of another frame of the animation.</p>
1225 * @param animation The animation which was repeated.
1227 void onAnimationUpdate(ValueAnimator animation
);
1232 * Return the number of animations currently running.
1234 * Used by StrictMode internally to annotate violations. Only
1235 * called on the main thread.
1239 public static int getCurrentAnimationsCount() {
1240 return sAnimations
.get().size();
1244 * Clear all animations on this thread, without canceling or ending them.
1245 * This should be used with caution.
1249 public static void clearAllAnimations() {
1250 sAnimations
.get().clear();
1251 sPendingAnimations
.get().clear();
1252 sDelayedAnims
.get().clear();
1256 public String
toString() {
1257 String returnVal
= "ValueAnimator@" + Integer
.toHexString(hashCode());
1258 if (mValues
!= null
) {
1259 for (int i
= 0; i
< mValues
.length
; ++i
) {
1260 returnVal
+= "\n " + mValues
[i
].toString();