d8a12c6882359e60b74f30ee68f85f1dd4d1ad29
[pub/Android/ownCloud.git] / actionbarsherlock / src / com / actionbarsherlock / internal / nineoldandroids / animation / ValueAnimator.java
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
17 package com.actionbarsherlock.internal.nineoldandroids.animation;
18
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;
27
28 import java.util.ArrayList;
29 import java.util.HashMap;
30
31 /**
32 * This class provides a simple timing engine for running animations
33 * which calculate animated values and set them on target objects.
34 *
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>
37 *
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>
42 */
43 @SuppressWarnings({"rawtypes", "unchecked"})
44 public class ValueAnimator extends Animator {
45
46 /**
47 * Internal constants
48 */
49
50 /*
51 * The default amount of time in ms between animation frames
52 */
53 private static final long DEFAULT_FRAME_DELAY = 10;
54
55 /**
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
58 */
59 static final int ANIMATION_START = 0;
60 static final int ANIMATION_FRAME = 1;
61
62 /**
63 * Values used with internal variable mPlayingState to indicate the current state of an
64 * animation.
65 */
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
69
70 /**
71 * Internal variables
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.
75 */
76
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
79 // to animateFrame()
80 long mStartTime;
81
82 /**
83 * Set when setCurrentPlayTime() is called. If negative, animation is not currently seeked
84 * to a value.
85 */
86 long mSeekTime = -1;
87
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.
92
93 // The static sAnimationHandler processes the internal timing loop on which all animations
94 // are based
95 private static ThreadLocal<AnimationHandler> sAnimationHandler =
96 new ThreadLocal<AnimationHandler>();
97
98 // The per-thread list of all active animations
99 private static final ThreadLocal<ArrayList<ValueAnimator>> sAnimations =
100 new ThreadLocal<ArrayList<ValueAnimator>>() {
101 @Override
102 protected ArrayList<ValueAnimator> initialValue() {
103 return new ArrayList<ValueAnimator>();
104 }
105 };
106
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>>() {
110 @Override
111 protected ArrayList<ValueAnimator> initialValue() {
112 return new ArrayList<ValueAnimator>();
113 }
114 };
115
116 /**
117 * Internal per-thread collections used to avoid set collisions as animations start and end
118 * while being processed.
119 */
120 private static final ThreadLocal<ArrayList<ValueAnimator>> sDelayedAnims =
121 new ThreadLocal<ArrayList<ValueAnimator>>() {
122 @Override
123 protected ArrayList<ValueAnimator> initialValue() {
124 return new ArrayList<ValueAnimator>();
125 }
126 };
127
128 private static final ThreadLocal<ArrayList<ValueAnimator>> sEndingAnims =
129 new ThreadLocal<ArrayList<ValueAnimator>>() {
130 @Override
131 protected ArrayList<ValueAnimator> initialValue() {
132 return new ArrayList<ValueAnimator>();
133 }
134 };
135
136 private static final ThreadLocal<ArrayList<ValueAnimator>> sReadyAnims =
137 new ThreadLocal<ArrayList<ValueAnimator>>() {
138 @Override
139 protected ArrayList<ValueAnimator> initialValue() {
140 return new ArrayList<ValueAnimator>();
141 }
142 };
143
144 // The time interpolator to be used if none is set on the animation
145 private static final /*Time*/Interpolator sDefaultInterpolator =
146 new AccelerateDecelerateInterpolator();
147
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();
151
152 /**
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.
155 */
156 private boolean mPlayingBackwards = false;
157
158 /**
159 * This variable tracks the current iteration that is playing. When mCurrentIteration exceeds the
160 * repeatCount (if repeatCount!=INFINITE), the animation ends
161 */
162 private int mCurrentIteration = 0;
163
164 /**
165 * Tracks current elapsed/eased fraction, for querying in getAnimatedFraction().
166 */
167 private float mCurrentFraction = 0f;
168
169 /**
170 * Tracks whether a startDelay'd animation has begun playing through the startDelay.
171 */
172 private boolean mStartedDelay = false;
173
174 /**
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
178 * animations list).
179 */
180 private long mDelayStartTime;
181
182 /**
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.
187 */
188 int mPlayingState = STOPPED;
189
190 /**
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.
197 */
198 private boolean mRunning = false;
199
200 /**
201 * Additional playing state to indicate whether an animator has been start()'d, whether or
202 * not there is a nonzero startDelay.
203 */
204 private boolean mStarted = false;
205
206 /**
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.
209 */
210 boolean mInitialized = false;
211
212 //
213 // Backing variables
214 //
215
216 // How long the animation should last in ms
217 private long mDuration = 300;
218
219 // The amount of time in ms to delay starting the animation after start() is called
220 private long mStartDelay = 0;
221
222 // The number of milliseconds between animation frames
223 private static long sFrameDelay = DEFAULT_FRAME_DELAY;
224
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;
228
229 /**
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.
233 */
234 private int mRepeatMode = RESTART;
235
236 /**
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.
240 */
241 private /*Time*/Interpolator mInterpolator = sDefaultInterpolator;
242
243 /**
244 * The set of listeners to be sent events through the life of an animation.
245 */
246 private ArrayList<AnimatorUpdateListener> mUpdateListeners = null;
247
248 /**
249 * The property/value sets being animated.
250 */
251 PropertyValuesHolder[] mValues;
252
253 /**
254 * A hashmap of the PropertyValuesHolder objects. This map is used to lookup animated values
255 * by property name during calls to getAnimatedValue(String).
256 */
257 HashMap<String, PropertyValuesHolder> mValuesMap;
258
259 /**
260 * Public constants
261 */
262
263 /**
264 * When the animation reaches the end and <code>repeatCount</code> is INFINITE
265 * or a positive value, the animation restarts from the beginning.
266 */
267 public static final int RESTART = 1;
268 /**
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.
271 */
272 public static final int REVERSE = 2;
273 /**
274 * This value used used with the {@link #setRepeatCount(int)} property to repeat
275 * the animation indefinitely.
276 */
277 public static final int INFINITE = -1;
278
279 /**
280 * Creates a new ValueAnimator object. This default constructor is primarily for
281 * use internally; the factory methods which take parameters are more generally
282 * useful.
283 */
284 public ValueAnimator() {
285 }
286
287 /**
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.
294 *
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.
297 */
298 public static ValueAnimator ofInt(int... values) {
299 ValueAnimator anim = new ValueAnimator();
300 anim.setIntValues(values);
301 return anim;
302 }
303
304 /**
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.
311 *
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.
314 */
315 public static ValueAnimator ofFloat(float... values) {
316 ValueAnimator anim = new ValueAnimator();
317 anim.setFloatValues(values);
318 return anim;
319 }
320
321 /**
322 * Constructs and returns a ValueAnimator that animates between the values
323 * specified in the PropertyValuesHolder objects.
324 *
325 * @param values A set of PropertyValuesHolder objects whose values will be animated
326 * between over time.
327 * @return A ValueAnimator object that is set up to animate between the given values.
328 */
329 public static ValueAnimator ofPropertyValuesHolder(PropertyValuesHolder... values) {
330 ValueAnimator anim = new ValueAnimator();
331 anim.setValues(values);
332 return anim;
333 }
334 /**
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.
341 *
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.
345 *
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
348 * value.
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.
351 */
352 public static ValueAnimator ofObject(TypeEvaluator evaluator, Object... values) {
353 ValueAnimator anim = new ValueAnimator();
354 anim.setObjectValues(values);
355 anim.setEvaluator(evaluator);
356 return anim;
357 }
358
359 /**
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.
366 *
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>
370 *
371 * @param values A set of values that the animation will animate between over time.
372 */
373 public void setIntValues(int... values) {
374 if (values == null || values.length == 0) {
375 return;
376 }
377 if (mValues == null || mValues.length == 0) {
378 setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofInt("", values)});
379 } else {
380 PropertyValuesHolder valuesHolder = mValues[0];
381 valuesHolder.setIntValues(values);
382 }
383 // New property/values/target should cause re-initialization prior to starting
384 mInitialized = false;
385 }
386
387 /**
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.
394 *
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>
398 *
399 * @param values A set of values that the animation will animate between over time.
400 */
401 public void setFloatValues(float... values) {
402 if (values == null || values.length == 0) {
403 return;
404 }
405 if (mValues == null || mValues.length == 0) {
406 setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofFloat("", values)});
407 } else {
408 PropertyValuesHolder valuesHolder = mValues[0];
409 valuesHolder.setFloatValues(values);
410 }
411 // New property/values/target should cause re-initialization prior to starting
412 mInitialized = false;
413 }
414
415 /**
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.
422 *
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>
426 *
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>
430 *
431 * @param values The set of values to animate between.
432 */
433 public void setObjectValues(Object... values) {
434 if (values == null || values.length == 0) {
435 return;
436 }
437 if (mValues == null || mValues.length == 0) {
438 setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofObject("",
439 (TypeEvaluator)null, values)});
440 } else {
441 PropertyValuesHolder valuesHolder = mValues[0];
442 valuesHolder.setObjectValues(values);
443 }
444 // New property/values/target should cause re-initialization prior to starting
445 mInitialized = false;
446 }
447
448 /**
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
452 * instead.
453 *
454 * @param values The set of values, per property, being animated between.
455 */
456 public void setValues(PropertyValuesHolder... values) {
457 int numValues = values.length;
458 mValues = values;
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);
463 }
464 // New property/values/target should cause re-initialization prior to starting
465 mInitialized = false;
466 }
467
468 /**
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.
472 *
473 * @return PropertyValuesHolder[] An array of PropertyValuesHolder objects which hold the
474 * values, per property, that define the animation.
475 */
476 public PropertyValuesHolder[] getValues() {
477 return mValues;
478 }
479
480 /**
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
485 * animation.
486 *
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>
489 */
490 void initAnimation() {
491 if (!mInitialized) {
492 int numValues = mValues.length;
493 for (int i = 0; i < numValues; ++i) {
494 mValues[i].init();
495 }
496 mInitialized = true;
497 }
498 }
499
500
501 /**
502 * Sets the length of the animation. The default duration is 300 milliseconds.
503 *
504 * @param duration The length of the animation, in milliseconds. This value cannot
505 * be negative.
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>.
509 */
510 public ValueAnimator setDuration(long duration) {
511 if (duration < 0) {
512 throw new IllegalArgumentException("Animators cannot have negative duration: " +
513 duration);
514 }
515 mDuration = duration;
516 return this;
517 }
518
519 /**
520 * Gets the length of the animation. The default duration is 300 milliseconds.
521 *
522 * @return The length of the animation, in milliseconds.
523 */
524 public long getDuration() {
525 return mDuration;
526 }
527
528 /**
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.
535 *
536 * @param playTime The time, in milliseconds, to which the animation is advanced or rewound.
537 */
538 public void setCurrentPlayTime(long playTime) {
539 initAnimation();
540 long currentTime = AnimationUtils.currentAnimationTimeMillis();
541 if (mPlayingState != RUNNING) {
542 mSeekTime = playTime;
543 mPlayingState = SEEKED;
544 }
545 mStartTime = currentTime - playTime;
546 animationFrame(currentTime);
547 }
548
549 /**
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.
553 *
554 * @return The current position in time of the animation.
555 */
556 public long getCurrentPlayTime() {
557 if (!mInitialized || mPlayingState == STOPPED) {
558 return 0;
559 }
560 return AnimationUtils.currentAnimationTimeMillis() - mStartTime;
561 }
562
563 /**
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.
569 *
570 */
571 private static class AnimationHandler extends Handler {
572 /**
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.
583 */
584 @Override
585 public void handleMessage(Message msg) {
586 boolean callAgain = true;
587 ArrayList<ValueAnimator> animations = sAnimations.get();
588 ArrayList<ValueAnimator> delayedAnims = sDelayedAnims.get();
589 switch (msg.what) {
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) {
595 callAgain = false;
596 }
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
601 // is empty.
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();
612 } else {
613 delayedAnims.add(anim);
614 }
615 }
616 }
617 // fall through to process first frame of new animations
618 case ANIMATION_FRAME:
619 // currentTime holds the common time for all animations processed
620 // during this frame
621 long currentTime = AnimationUtils.currentAnimationTimeMillis();
622 ArrayList<ValueAnimator> readyAnims = sReadyAnims.get();
623 ArrayList<ValueAnimator> endingAnims = sEndingAnims.get();
624
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);
632 }
633 }
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);
641 }
642 readyAnims.clear();
643 }
644
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();
648 int i = 0;
649 while (i < numAnims) {
650 ValueAnimator anim = animations.get(i);
651 if (anim.animationFrame(currentTime)) {
652 endingAnims.add(anim);
653 }
654 if (animations.size() == numAnims) {
655 ++i;
656 } else {
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
663 // be nice to avoid.
664 --numAnims;
665 endingAnims.remove(anim);
666 }
667 }
668 if (endingAnims.size() > 0) {
669 for (i = 0; i < endingAnims.size(); ++i) {
670 endingAnims.get(i).endAnimation();
671 }
672 endingAnims.clear();
673 }
674
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)));
680 }
681 break;
682 }
683 }
684 }
685
686 /**
687 * The amount of time, in milliseconds, to delay starting the animation after
688 * {@link #start()} is called.
689 *
690 * @return the number of milliseconds to delay running the animation
691 */
692 public long getStartDelay() {
693 return mStartDelay;
694 }
695
696 /**
697 * The amount of time, in milliseconds, to delay starting the animation after
698 * {@link #start()} is called.
699
700 * @param startDelay The amount of the delay, in milliseconds
701 */
702 public void setStartDelay(long startDelay) {
703 this.mStartDelay = startDelay;
704 }
705
706 /**
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.
712 *
713 * @return the requested time between frames, in milliseconds
714 */
715 public static long getFrameDelay() {
716 return sFrameDelay;
717 }
718
719 /**
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.
725 *
726 * @param frameDelay the requested time between frames, in milliseconds
727 */
728 public static void setFrameDelay(long frameDelay) {
729 sFrameDelay = frameDelay;
730 }
731
732 /**
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.
738 *
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.
743 */
744 public Object getAnimatedValue() {
745 if (mValues != null && mValues.length > 0) {
746 return mValues[0].getAnimatedValue();
747 }
748 // Shouldn't get here; should always have values unless ValueAnimator was set up wrong
749 return null;
750 }
751
752 /**
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.
758 *
759 * @return animatedValue The value most recently calculated for the named property
760 * by this <code>ValueAnimator</code>.
761 */
762 public Object getAnimatedValue(String propertyName) {
763 PropertyValuesHolder valuesHolder = mValuesMap.get(propertyName);
764 if (valuesHolder != null) {
765 return valuesHolder.getAnimatedValue();
766 } else {
767 // At least avoid crashing if called with bogus propertyName
768 return null;
769 }
770 }
771
772 /**
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.
777 *
778 * @param value the number of times the animation should be repeated
779 */
780 public void setRepeatCount(int value) {
781 mRepeatCount = value;
782 }
783 /**
784 * Defines how many times the animation should repeat. The default value
785 * is 0.
786 *
787 * @return the number of times the animation should repeat, or {@link #INFINITE}
788 */
789 public int getRepeatCount() {
790 return mRepeatCount;
791 }
792
793 /**
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}.
797 *
798 * @param value {@link #RESTART} or {@link #REVERSE}
799 */
800 public void setRepeatMode(int value) {
801 mRepeatMode = value;
802 }
803
804 /**
805 * Defines what this animation should do when it reaches the end.
806 *
807 * @return either one of {@link #REVERSE} or {@link #RESTART}
808 */
809 public int getRepeatMode() {
810 return mRepeatMode;
811 }
812
813 /**
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.
817 *
818 * @param listener the listener to be added to the current set of listeners for this animation.
819 */
820 public void addUpdateListener(AnimatorUpdateListener listener) {
821 if (mUpdateListeners == null) {
822 mUpdateListeners = new ArrayList<AnimatorUpdateListener>();
823 }
824 mUpdateListeners.add(listener);
825 }
826
827 /**
828 * Removes all listeners from the set listening to frame updates for this animation.
829 */
830 public void removeAllUpdateListeners() {
831 if (mUpdateListeners == null) {
832 return;
833 }
834 mUpdateListeners.clear();
835 mUpdateListeners = null;
836 }
837
838 /**
839 * Removes a listener from the set listening to frame updates for this animation.
840 *
841 * @param listener the listener to be removed from the current set of update listeners
842 * for this animation.
843 */
844 public void removeUpdateListener(AnimatorUpdateListener listener) {
845 if (mUpdateListeners == null) {
846 return;
847 }
848 mUpdateListeners.remove(listener);
849 if (mUpdateListeners.size() == 0) {
850 mUpdateListeners = null;
851 }
852 }
853
854
855 /**
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}
860 *
861 * @param value the interpolator to be used by this animation. A value of <code>null</code>
862 * will result in linear interpolation.
863 */
864 @Override
865 public void setInterpolator(/*Time*/Interpolator value) {
866 if (value != null) {
867 mInterpolator = value;
868 } else {
869 mInterpolator = new LinearInterpolator();
870 }
871 }
872
873 /**
874 * Returns the timing interpolator that this ValueAnimator uses.
875 *
876 * @return The timing interpolator for this ValueAnimator.
877 */
878 public /*Time*/Interpolator getInterpolator() {
879 return mInterpolator;
880 }
881
882 /**
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.
890 *
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>
895 *
896 * @param value the evaluator to be used this animation
897 */
898 public void setEvaluator(TypeEvaluator value) {
899 if (value != null && mValues != null && mValues.length > 0) {
900 mValues[0].setEvaluator(value);
901 }
902 }
903
904 /**
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.
908 *
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>
914 *
915 * @param playBackwards Whether the ValueAnimator should start playing in reverse.
916 */
917 private void start(boolean playBackwards) {
918 if (Looper.myLooper() == null) {
919 throw new AndroidRuntimeException("Animators may only be run on Looper threads");
920 }
921 mPlayingBackwards = playBackwards;
922 mCurrentIteration = 0;
923 mPlayingState = STOPPED;
924 mStarted = true;
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;
931 mRunning = true;
932
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);
939 }
940 }
941 }
942 AnimationHandler animationHandler = sAnimationHandler.get();
943 if (animationHandler == null) {
944 animationHandler = new AnimationHandler();
945 sAnimationHandler.set(animationHandler);
946 }
947 animationHandler.sendEmptyMessage(ANIMATION_START);
948 }
949
950 @Override
951 public void start() {
952 start(false);
953 }
954
955 @Override
956 public void cancel() {
957 // Only cancel if the animation is actually running or has been started and is about
958 // to run
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);
967 }
968 }
969 endAnimation();
970 }
971 }
972
973 @Override
974 public void end() {
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;
978 startAnimation();
979 } else if (!mInitialized) {
980 initAnimation();
981 }
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) {
985 animateValue(0f);
986 } else {
987 animateValue(1f);
988 }
989 endAnimation();
990 }
991
992 @Override
993 public boolean isRunning() {
994 return (mPlayingState == RUNNING || mRunning);
995 }
996
997 @Override
998 public boolean isStarted() {
999 return mStarted;
1000 }
1001
1002 /**
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.
1008 */
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;
1016 } else {
1017 start(true);
1018 }
1019 }
1020
1021 /**
1022 * Called internally to end an animation by removing it from the animations list. Must be
1023 * called on the UI thread.
1024 */
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);
1036 }
1037 }
1038 mRunning = false;
1039 mStarted = false;
1040 }
1041
1042 /**
1043 * Called internally to start an animation by adding it to the active animations list. Must be
1044 * called on the UI thread.
1045 */
1046 private void startAnimation() {
1047 initAnimation();
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);
1057 }
1058 }
1059 }
1060
1061 /**
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.
1065 *
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.
1070 */
1071 private boolean delayedAnimationFrame(long currentTime) {
1072 if (!mStartedDelay) {
1073 mStartedDelay = true;
1074 mDelayStartTime = currentTime;
1075 } else {
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;
1082 return true;
1083 }
1084 }
1085 return false;
1086 }
1087
1088 /**
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).
1095 *
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.
1099 */
1100 boolean animationFrame(long currentTime) {
1101 boolean done = false;
1102
1103 if (mPlayingState == STOPPED) {
1104 mPlayingState = RUNNING;
1105 if (mSeekTime < 0) {
1106 mStartTime = currentTime;
1107 } else {
1108 mStartTime = currentTime - mSeekTime;
1109 // Now that we're playing, reset the seek time
1110 mSeekTime = -1;
1111 }
1112 }
1113 switch (mPlayingState) {
1114 case RUNNING:
1115 case SEEKED:
1116 float fraction = mDuration > 0 ? (float)(currentTime - mStartTime) / mDuration : 1f;
1117 if (fraction >= 1f) {
1118 if (mCurrentIteration < mRepeatCount || mRepeatCount == INFINITE) {
1119 // Time to repeat
1120 if (mListeners != null) {
1121 int numListeners = mListeners.size();
1122 for (int i = 0; i < numListeners; ++i) {
1123 mListeners.get(i).onAnimationRepeat(this);
1124 }
1125 }
1126 if (mRepeatMode == REVERSE) {
1127 mPlayingBackwards = mPlayingBackwards ? false : true;
1128 }
1129 mCurrentIteration += (int)fraction;
1130 fraction = fraction % 1f;
1131 mStartTime += mDuration;
1132 } else {
1133 done = true;
1134 fraction = Math.min(fraction, 1.0f);
1135 }
1136 }
1137 if (mPlayingBackwards) {
1138 fraction = 1f - fraction;
1139 }
1140 animateValue(fraction);
1141 break;
1142 }
1143
1144 return done;
1145 }
1146
1147 /**
1148 * Returns the current animation fraction, which is the elapsed/interpolated fraction used in
1149 * the most recent frame update on the animation.
1150 *
1151 * @return Elapsed/interpolated fraction of the animation.
1152 */
1153 public float getAnimatedFraction() {
1154 return mCurrentFraction;
1155 }
1156
1157 /**
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.
1163 *
1164 * <p>Overrides of this method must call the superclass to perform the calculation
1165 * of the animated value.</p>
1166 *
1167 * @param fraction The elapsed fraction of the animation.
1168 */
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);
1175 }
1176 if (mUpdateListeners != null) {
1177 int numListeners = mUpdateListeners.size();
1178 for (int i = 0; i < numListeners; ++i) {
1179 mUpdateListeners.get(i).onAnimationUpdate(this);
1180 }
1181 }
1182 }
1183
1184 @Override
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));
1193 }
1194 }
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);
1210 }
1211 }
1212 return anim;
1213 }
1214
1215 /**
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>.
1220 */
1221 public static interface AnimatorUpdateListener {
1222 /**
1223 * <p>Notifies the occurrence of another frame of the animation.</p>
1224 *
1225 * @param animation The animation which was repeated.
1226 */
1227 void onAnimationUpdate(ValueAnimator animation);
1228
1229 }
1230
1231 /**
1232 * Return the number of animations currently running.
1233 *
1234 * Used by StrictMode internally to annotate violations. Only
1235 * called on the main thread.
1236 *
1237 * @hide
1238 */
1239 public static int getCurrentAnimationsCount() {
1240 return sAnimations.get().size();
1241 }
1242
1243 /**
1244 * Clear all animations on this thread, without canceling or ending them.
1245 * This should be used with caution.
1246 *
1247 * @hide
1248 */
1249 public static void clearAllAnimations() {
1250 sAnimations.get().clear();
1251 sPendingAnimations.get().clear();
1252 sDelayedAnims.get().clear();
1253 }
1254
1255 @Override
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();
1261 }
1262 }
1263 return returnVal;
1264 }
1265 }