PageRenderTime 56ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/src/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator.java

https://bitbucket.org/fredgrott/gwsamulet
Java | 1321 lines | 576 code | 102 blank | 643 comment | 149 complexity | cf96f1f0939d5bf94d4d08233768f8fe MD5 | raw file

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file