AnimatorSet.java revision 7dfacdb1c820f955cb3cd6032ff5fbc2dd7d9df5
1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.animation; 18 19import java.util.ArrayList; 20import java.util.Collection; 21import java.util.HashMap; 22import java.util.List; 23 24/** 25 * This class plays a set of {@link Animator} objects in the specified order. Animations 26 * can be set up to play together, in sequence, or after a specified delay. 27 * 28 * <p>There are two different approaches to adding animations to a <code>AnimatorSet</code>: 29 * either the {@link AnimatorSet#playTogether(Animator[]) playTogether()} or 30 * {@link AnimatorSet#playSequentially(Animator[]) playSequentially()} methods can be called to add 31 * a set of animations all at once, or the {@link AnimatorSet#play(Animator)} can be 32 * used in conjunction with methods in the {@link AnimatorSet.Builder Builder} 33 * class to add animations 34 * one by one.</p> 35 * 36 * <p>It is possible to set up a <code>AnimatorSet</code> with circular dependencies between 37 * its animations. For example, an animation a1 could be set up to start before animation a2, a2 38 * before a3, and a3 before a1. The results of this configuration are undefined, but will typically 39 * result in none of the affected animations being played. Because of this (and because 40 * circular dependencies do not make logical sense anyway), circular dependencies 41 * should be avoided, and the dependency flow of animations should only be in one direction. 42 */ 43public final class AnimatorSet extends Animator { 44 45 /** 46 * Internal variables 47 * NOTE: This object implements the clone() method, making a deep copy of any referenced 48 * objects. As other non-trivial fields are added to this class, make sure to add logic 49 * to clone() to make deep copies of them. 50 */ 51 52 /** 53 * Tracks animations currently being played, so that we know what to 54 * cancel or end when cancel() or end() is called on this AnimatorSet 55 */ 56 private ArrayList<Animator> mPlayingSet = new ArrayList<Animator>(); 57 58 /** 59 * Contains all nodes, mapped to their respective Animators. When new 60 * dependency information is added for an Animator, we want to add it 61 * to a single node representing that Animator, not create a new Node 62 * if one already exists. 63 */ 64 private HashMap<Animator, Node> mNodeMap = new HashMap<Animator, Node>(); 65 66 /** 67 * Set of all nodes created for this AnimatorSet. This list is used upon 68 * starting the set, and the nodes are placed in sorted order into the 69 * sortedNodes collection. 70 */ 71 private ArrayList<Node> mNodes = new ArrayList<Node>(); 72 73 /** 74 * The sorted list of nodes. This is the order in which the animations will 75 * be played. The details about when exactly they will be played depend 76 * on the dependency relationships of the nodes. 77 */ 78 private ArrayList<Node> mSortedNodes = new ArrayList<Node>(); 79 80 /** 81 * Flag indicating whether the nodes should be sorted prior to playing. This 82 * flag allows us to cache the previous sorted nodes so that if the sequence 83 * is replayed with no changes, it does not have to re-sort the nodes again. 84 */ 85 private boolean mNeedsSort = true; 86 87 private AnimatorSetListener mSetListener = null; 88 89 /** 90 * Flag indicating that the AnimatorSet has been manually 91 * terminated (by calling cancel() or end()). 92 * This flag is used to avoid starting other animations when currently-playing 93 * child animations of this AnimatorSet end. It also determines whether cancel/end 94 * notifications are sent out via the normal AnimatorSetListener mechanism. 95 */ 96 boolean mTerminated = false; 97 98 // The amount of time in ms to delay starting the animation after start() is called 99 private long mStartDelay = 0; 100 101 // Animator used for a nonzero startDelay 102 private ValueAnimator mDelayAnim = null; 103 104 105 // How long the child animations should last in ms. The default value is negative, which 106 // simply means that there is no duration set on the AnimatorSet. When a real duration is 107 // set, it is passed along to the child animations. 108 private long mDuration = -1; 109 110 111 /** 112 * Sets up this AnimatorSet to play all of the supplied animations at the same time. 113 * 114 * @param items The animations that will be started simultaneously. 115 */ 116 public void playTogether(Animator... items) { 117 if (items != null) { 118 mNeedsSort = true; 119 Builder builder = play(items[0]); 120 for (int i = 1; i < items.length; ++i) { 121 builder.with(items[i]); 122 } 123 } 124 } 125 126 /** 127 * Sets up this AnimatorSet to play all of the supplied animations at the same time. 128 * 129 * @param items The animations that will be started simultaneously. 130 */ 131 public void playTogether(Collection<Animator> items) { 132 if (items != null && items.size() > 0) { 133 mNeedsSort = true; 134 Builder builder = null; 135 for (Animator anim : items) { 136 if (builder == null) { 137 builder = play(anim); 138 } else { 139 builder.with(anim); 140 } 141 } 142 } 143 } 144 145 /** 146 * Sets up this AnimatorSet to play each of the supplied animations when the 147 * previous animation ends. 148 * 149 * @param items The animations that will be started one after another. 150 */ 151 public void playSequentially(Animator... items) { 152 if (items != null) { 153 mNeedsSort = true; 154 if (items.length == 1) { 155 play(items[0]); 156 } else { 157 for (int i = 0; i < items.length - 1; ++i) { 158 play(items[i]).before(items[i+1]); 159 } 160 } 161 } 162 } 163 164 /** 165 * Sets up this AnimatorSet to play each of the supplied animations when the 166 * previous animation ends. 167 * 168 * @param items The animations that will be started one after another. 169 */ 170 public void playSequentially(List<Animator> items) { 171 if (items != null && items.size() > 0) { 172 mNeedsSort = true; 173 if (items.size() == 1) { 174 play(items.get(0)); 175 } else { 176 for (int i = 0; i < items.size() - 1; ++i) { 177 play(items.get(i)).before(items.get(i+1)); 178 } 179 } 180 } 181 } 182 183 /** 184 * Returns the current list of child Animator objects controlled by this 185 * AnimatorSet. This is a copy of the internal list; modifications to the returned list 186 * will not affect the AnimatorSet, although changes to the underlying Animator objects 187 * will affect those objects being managed by the AnimatorSet. 188 * 189 * @return ArrayList<Animator> The list of child animations of this AnimatorSet. 190 */ 191 public ArrayList<Animator> getChildAnimations() { 192 ArrayList<Animator> childList = new ArrayList<Animator>(); 193 for (Node node : mNodes) { 194 childList.add(node.animation); 195 } 196 return childList; 197 } 198 199 /** 200 * Sets the target object for all current {@link #getChildAnimations() child animations} 201 * of this AnimatorSet that take targets ({@link ObjectAnimator} and 202 * AnimatorSet). 203 * 204 * @param target The object being animated 205 */ 206 @Override 207 public void setTarget(Object target) { 208 for (Node node : mNodes) { 209 Animator animation = node.animation; 210 if (animation instanceof AnimatorSet) { 211 ((AnimatorSet)animation).setTarget(target); 212 } else if (animation instanceof ObjectAnimator) { 213 ((ObjectAnimator)animation).setTarget(target); 214 } 215 } 216 } 217 218 /** 219 * Sets the TimeInterpolator for all current {@link #getChildAnimations() child animations} 220 * of this AnimatorSet. 221 * 222 * @param interpolator the interpolator to be used by each child animation of this AnimatorSet 223 */ 224 @Override 225 public void setInterpolator(TimeInterpolator interpolator) { 226 for (Node node : mNodes) { 227 node.animation.setInterpolator(interpolator); 228 } 229 } 230 231 /** 232 * This method creates a <code>Builder</code> object, which is used to 233 * set up playing constraints. This initial <code>play()</code> method 234 * tells the <code>Builder</code> the animation that is the dependency for 235 * the succeeding commands to the <code>Builder</code>. For example, 236 * calling <code>play(a1).with(a2)</code> sets up the AnimatorSet to play 237 * <code>a1</code> and <code>a2</code> at the same time, 238 * <code>play(a1).before(a2)</code> sets up the AnimatorSet to play 239 * <code>a1</code> first, followed by <code>a2</code>, and 240 * <code>play(a1).after(a2)</code> sets up the AnimatorSet to play 241 * <code>a2</code> first, followed by <code>a1</code>. 242 * 243 * <p>Note that <code>play()</code> is the only way to tell the 244 * <code>Builder</code> the animation upon which the dependency is created, 245 * so successive calls to the various functions in <code>Builder</code> 246 * will all refer to the initial parameter supplied in <code>play()</code> 247 * as the dependency of the other animations. For example, calling 248 * <code>play(a1).before(a2).before(a3)</code> will play both <code>a2</code> 249 * and <code>a3</code> when a1 ends; it does not set up a dependency between 250 * <code>a2</code> and <code>a3</code>.</p> 251 * 252 * @param anim The animation that is the dependency used in later calls to the 253 * methods in the returned <code>Builder</code> object. A null parameter will result 254 * in a null <code>Builder</code> return value. 255 * @return Builder The object that constructs the AnimatorSet based on the dependencies 256 * outlined in the calls to <code>play</code> and the other methods in the 257 * <code>Builder</code object. 258 */ 259 public Builder play(Animator anim) { 260 if (anim != null) { 261 mNeedsSort = true; 262 return new Builder(anim); 263 } 264 return null; 265 } 266 267 /** 268 * {@inheritDoc} 269 * 270 * <p>Note that canceling a <code>AnimatorSet</code> also cancels all of the animations that it is 271 * responsible for.</p> 272 */ 273 @SuppressWarnings("unchecked") 274 @Override 275 public void cancel() { 276 mTerminated = true; 277 if (isRunning()) { 278 ArrayList<AnimatorListener> tmpListeners = null; 279 if (mListeners != null) { 280 tmpListeners = (ArrayList<AnimatorListener>) mListeners.clone(); 281 for (AnimatorListener listener : tmpListeners) { 282 listener.onAnimationCancel(this); 283 } 284 } 285 if (mDelayAnim != null && mDelayAnim.isRunning()) { 286 // If we're currently in the startDelay period, just cancel that animator and 287 // send out the end event to all listeners 288 mDelayAnim.cancel(); 289 } else if (mSortedNodes.size() > 0) { 290 for (Node node : mSortedNodes) { 291 node.animation.cancel(); 292 } 293 } 294 if (tmpListeners != null) { 295 for (AnimatorListener listener : tmpListeners) { 296 listener.onAnimationEnd(this); 297 } 298 } 299 } 300 } 301 302 /** 303 * {@inheritDoc} 304 * 305 * <p>Note that ending a <code>AnimatorSet</code> also ends all of the animations that it is 306 * responsible for.</p> 307 */ 308 @Override 309 public void end() { 310 mTerminated = true; 311 if (isRunning()) { 312 if (mSortedNodes.size() != mNodes.size()) { 313 // hasn't been started yet - sort the nodes now, then end them 314 sortNodes(); 315 for (Node node : mSortedNodes) { 316 if (mSetListener == null) { 317 mSetListener = new AnimatorSetListener(this); 318 } 319 node.animation.addListener(mSetListener); 320 } 321 } 322 if (mDelayAnim != null) { 323 mDelayAnim.cancel(); 324 } 325 if (mSortedNodes.size() > 0) { 326 for (Node node : mSortedNodes) { 327 node.animation.end(); 328 } 329 } 330 if (mListeners != null) { 331 ArrayList<AnimatorListener> tmpListeners = 332 (ArrayList<AnimatorListener>) mListeners.clone(); 333 for (AnimatorListener listener : tmpListeners) { 334 listener.onAnimationEnd(this); 335 } 336 } 337 } 338 } 339 340 /** 341 * Returns true if any of the child animations of this AnimatorSet have been started and have not 342 * yet ended. 343 * @return Whether this AnimatorSet has been started and has not yet ended. 344 */ 345 @Override 346 public boolean isRunning() { 347 for (Node node : mNodes) { 348 if (node.animation.isRunning()) { 349 return true; 350 } 351 } 352 return false; 353 } 354 355 /** 356 * The amount of time, in milliseconds, to delay starting the animation after 357 * {@link #start()} is called. 358 * 359 * @return the number of milliseconds to delay running the animation 360 */ 361 @Override 362 public long getStartDelay() { 363 return mStartDelay; 364 } 365 366 /** 367 * The amount of time, in milliseconds, to delay starting the animation after 368 * {@link #start()} is called. 369 370 * @param startDelay The amount of the delay, in milliseconds 371 */ 372 @Override 373 public void setStartDelay(long startDelay) { 374 mStartDelay = startDelay; 375 } 376 377 /** 378 * Gets the length of each of the child animations of this AnimatorSet. This value may 379 * be less than 0, which indicates that no duration has been set on this AnimatorSet 380 * and each of the child animations will use their own duration. 381 * 382 * @return The length of the animation, in milliseconds, of each of the child 383 * animations of this AnimatorSet. 384 */ 385 @Override 386 public long getDuration() { 387 return mDuration; 388 } 389 390 /** 391 * Sets the length of each of the current child animations of this AnimatorSet. By default, 392 * each child animation will use its own duration. If the duration is set on the AnimatorSet, 393 * then each child animation inherits this duration. 394 * 395 * @param duration The length of the animation, in milliseconds, of each of the child 396 * animations of this AnimatorSet. 397 */ 398 @Override 399 public AnimatorSet setDuration(long duration) { 400 if (duration < 0) { 401 throw new IllegalArgumentException("duration must be a value of zero or greater"); 402 } 403 for (Node node : mNodes) { 404 // TODO: don't set the duration of the timing-only nodes created by AnimatorSet to 405 // insert "play-after" delays 406 node.animation.setDuration(duration); 407 } 408 mDuration = duration; 409 return this; 410 } 411 412 @Override 413 public void setupStartValues() { 414 for (Node node : mNodes) { 415 node.animation.setupStartValues(); 416 } 417 } 418 419 @Override 420 public void setupEndValues() { 421 for (Node node : mNodes) { 422 node.animation.setupEndValues(); 423 } 424 } 425 426 /** 427 * {@inheritDoc} 428 * 429 * <p>Starting this <code>AnimatorSet</code> will, in turn, start the animations for which 430 * it is responsible. The details of when exactly those animations are started depends on 431 * the dependency relationships that have been set up between the animations. 432 */ 433 @SuppressWarnings("unchecked") 434 @Override 435 public void start() { 436 mTerminated = false; 437 438 // First, sort the nodes (if necessary). This will ensure that sortedNodes 439 // contains the animation nodes in the correct order. 440 sortNodes(); 441 442 int numSortedNodes = mSortedNodes.size(); 443 for (int i = 0; i < numSortedNodes; ++i) { 444 Node node = mSortedNodes.get(i); 445 // First, clear out the old listeners 446 ArrayList<AnimatorListener> oldListeners = node.animation.getListeners(); 447 if (oldListeners != null && oldListeners.size() > 0) { 448 for (AnimatorListener listener : oldListeners) { 449 if (listener instanceof DependencyListener || 450 listener instanceof AnimatorSetListener) { 451 node.animation.removeListener(listener); 452 } 453 } 454 } 455 } 456 457 // nodesToStart holds the list of nodes to be started immediately. We don't want to 458 // start the animations in the loop directly because we first need to set up 459 // dependencies on all of the nodes. For example, we don't want to start an animation 460 // when some other animation also wants to start when the first animation begins. 461 final ArrayList<Node> nodesToStart = new ArrayList<Node>(); 462 for (int i = 0; i < numSortedNodes; ++i) { 463 Node node = mSortedNodes.get(i); 464 if (mSetListener == null) { 465 mSetListener = new AnimatorSetListener(this); 466 } 467 if (node.dependencies == null || node.dependencies.size() == 0) { 468 nodesToStart.add(node); 469 } else { 470 int numDependencies = node.dependencies.size(); 471 for (int j = 0; j < numDependencies; ++j) { 472 Dependency dependency = node.dependencies.get(j); 473 dependency.node.animation.addListener( 474 new DependencyListener(this, node, dependency.rule)); 475 } 476 node.tmpDependencies = (ArrayList<Dependency>) node.dependencies.clone(); 477 } 478 node.animation.addListener(mSetListener); 479 } 480 // Now that all dependencies are set up, start the animations that should be started. 481 if (mStartDelay <= 0) { 482 for (Node node : nodesToStart) { 483 node.animation.start(); 484 mPlayingSet.add(node.animation); 485 } 486 } else { 487 // TODO: Need to cancel out of the delay appropriately 488 mDelayAnim = ValueAnimator.ofFloat(0f, 1f); 489 mDelayAnim.setDuration(mStartDelay); 490 mDelayAnim.addListener(new AnimatorListenerAdapter() { 491 boolean canceled = false; 492 public void onAnimationCancel(Animator anim) { 493 canceled = true; 494 } 495 public void onAnimationEnd(Animator anim) { 496 if (!canceled) { 497 int numNodes = nodesToStart.size(); 498 for (int i = 0; i < numNodes; ++i) { 499 Node node = nodesToStart.get(i); 500 node.animation.start(); 501 mPlayingSet.add(node.animation); 502 } 503 } 504 } 505 }); 506 mDelayAnim.start(); 507 } 508 if (mListeners != null) { 509 ArrayList<AnimatorListener> tmpListeners = 510 (ArrayList<AnimatorListener>) mListeners.clone(); 511 int numListeners = tmpListeners.size(); 512 for (int i = 0; i < numListeners; ++i) { 513 tmpListeners.get(i).onAnimationStart(this); 514 if (mNodes.size() == 0) { 515 // Handle unusual case where empty AnimatorSet is started - should send out 516 // end event immediately since the event will not be sent out at all otherwise 517 tmpListeners.get(i).onAnimationEnd(this); 518 } 519 } 520 } 521 } 522 523 @Override 524 public AnimatorSet clone() { 525 final AnimatorSet anim = (AnimatorSet) super.clone(); 526 /* 527 * The basic clone() operation copies all items. This doesn't work very well for 528 * AnimatorSet, because it will copy references that need to be recreated and state 529 * that may not apply. What we need to do now is put the clone in an uninitialized 530 * state, with fresh, empty data structures. Then we will build up the nodes list 531 * manually, as we clone each Node (and its animation). The clone will then be sorted, 532 * and will populate any appropriate lists, when it is started. 533 */ 534 anim.mNeedsSort = true; 535 anim.mTerminated = false; 536 anim.mPlayingSet = new ArrayList<Animator>(); 537 anim.mNodeMap = new HashMap<Animator, Node>(); 538 anim.mNodes = new ArrayList<Node>(); 539 anim.mSortedNodes = new ArrayList<Node>(); 540 541 // Walk through the old nodes list, cloning each node and adding it to the new nodemap. 542 // One problem is that the old node dependencies point to nodes in the old AnimatorSet. 543 // We need to track the old/new nodes in order to reconstruct the dependencies in the clone. 544 HashMap<Node, Node> nodeCloneMap = new HashMap<Node, Node>(); // <old, new> 545 for (Node node : mNodes) { 546 Node nodeClone = node.clone(); 547 nodeCloneMap.put(node, nodeClone); 548 anim.mNodes.add(nodeClone); 549 anim.mNodeMap.put(nodeClone.animation, nodeClone); 550 // Clear out the dependencies in the clone; we'll set these up manually later 551 nodeClone.dependencies = null; 552 nodeClone.tmpDependencies = null; 553 nodeClone.nodeDependents = null; 554 nodeClone.nodeDependencies = null; 555 // clear out any listeners that were set up by the AnimatorSet; these will 556 // be set up when the clone's nodes are sorted 557 ArrayList<AnimatorListener> cloneListeners = nodeClone.animation.getListeners(); 558 if (cloneListeners != null) { 559 ArrayList<AnimatorListener> listenersToRemove = null; 560 for (AnimatorListener listener : cloneListeners) { 561 if (listener instanceof AnimatorSetListener) { 562 if (listenersToRemove == null) { 563 listenersToRemove = new ArrayList<AnimatorListener>(); 564 } 565 listenersToRemove.add(listener); 566 } 567 } 568 if (listenersToRemove != null) { 569 for (AnimatorListener listener : listenersToRemove) { 570 cloneListeners.remove(listener); 571 } 572 } 573 } 574 } 575 // Now that we've cloned all of the nodes, we're ready to walk through their 576 // dependencies, mapping the old dependencies to the new nodes 577 for (Node node : mNodes) { 578 Node nodeClone = nodeCloneMap.get(node); 579 if (node.dependencies != null) { 580 for (Dependency dependency : node.dependencies) { 581 Node clonedDependencyNode = nodeCloneMap.get(dependency.node); 582 Dependency cloneDependency = new Dependency(clonedDependencyNode, 583 dependency.rule); 584 nodeClone.addDependency(cloneDependency); 585 } 586 } 587 } 588 589 return anim; 590 } 591 592 /** 593 * This class is the mechanism by which animations are started based on events in other 594 * animations. If an animation has multiple dependencies on other animations, then 595 * all dependencies must be satisfied before the animation is started. 596 */ 597 private static class DependencyListener implements AnimatorListener { 598 599 private AnimatorSet mAnimatorSet; 600 601 // The node upon which the dependency is based. 602 private Node mNode; 603 604 // The Dependency rule (WITH or AFTER) that the listener should wait for on 605 // the node 606 private int mRule; 607 608 public DependencyListener(AnimatorSet animatorSet, Node node, int rule) { 609 this.mAnimatorSet = animatorSet; 610 this.mNode = node; 611 this.mRule = rule; 612 } 613 614 /** 615 * Ignore cancel events for now. We may want to handle this eventually, 616 * to prevent follow-on animations from running when some dependency 617 * animation is canceled. 618 */ 619 public void onAnimationCancel(Animator animation) { 620 } 621 622 /** 623 * An end event is received - see if this is an event we are listening for 624 */ 625 public void onAnimationEnd(Animator animation) { 626 if (mRule == Dependency.AFTER) { 627 startIfReady(animation); 628 } 629 } 630 631 /** 632 * Ignore repeat events for now 633 */ 634 public void onAnimationRepeat(Animator animation) { 635 } 636 637 /** 638 * A start event is received - see if this is an event we are listening for 639 */ 640 public void onAnimationStart(Animator animation) { 641 if (mRule == Dependency.WITH) { 642 startIfReady(animation); 643 } 644 } 645 646 /** 647 * Check whether the event received is one that the node was waiting for. 648 * If so, mark it as complete and see whether it's time to start 649 * the animation. 650 * @param dependencyAnimation the animation that sent the event. 651 */ 652 private void startIfReady(Animator dependencyAnimation) { 653 if (mAnimatorSet.mTerminated) { 654 // if the parent AnimatorSet was canceled, then don't start any dependent anims 655 return; 656 } 657 Dependency dependencyToRemove = null; 658 int numDependencies = mNode.tmpDependencies.size(); 659 for (int i = 0; i < numDependencies; ++i) { 660 Dependency dependency = mNode.tmpDependencies.get(i); 661 if (dependency.rule == mRule && 662 dependency.node.animation == dependencyAnimation) { 663 // rule fired - remove the dependency and listener and check to 664 // see whether it's time to start the animation 665 dependencyToRemove = dependency; 666 dependencyAnimation.removeListener(this); 667 break; 668 } 669 } 670 mNode.tmpDependencies.remove(dependencyToRemove); 671 if (mNode.tmpDependencies.size() == 0) { 672 // all dependencies satisfied: start the animation 673 mNode.animation.start(); 674 mAnimatorSet.mPlayingSet.add(mNode.animation); 675 } 676 } 677 678 } 679 680 private class AnimatorSetListener implements AnimatorListener { 681 682 private AnimatorSet mAnimatorSet; 683 684 AnimatorSetListener(AnimatorSet animatorSet) { 685 mAnimatorSet = animatorSet; 686 } 687 688 public void onAnimationCancel(Animator animation) { 689 if (!mTerminated) { 690 // Listeners are already notified of the AnimatorSet canceling in cancel(). 691 // The logic below only kicks in when animations end normally 692 if (mPlayingSet.size() == 0) { 693 if (mListeners != null) { 694 int numListeners = mListeners.size(); 695 for (int i = 0; i < numListeners; ++i) { 696 mListeners.get(i).onAnimationCancel(mAnimatorSet); 697 } 698 } 699 } 700 } 701 } 702 703 @SuppressWarnings("unchecked") 704 public void onAnimationEnd(Animator animation) { 705 animation.removeListener(this); 706 mPlayingSet.remove(animation); 707 Node animNode = mAnimatorSet.mNodeMap.get(animation); 708 animNode.done = true; 709 if (!mTerminated) { 710 // Listeners are already notified of the AnimatorSet ending in cancel() or 711 // end(); the logic below only kicks in when animations end normally 712 ArrayList<Node> sortedNodes = mAnimatorSet.mSortedNodes; 713 boolean allDone = true; 714 int numSortedNodes = sortedNodes.size(); 715 for (int i = 0; i < numSortedNodes; ++i) { 716 if (!sortedNodes.get(i).done) { 717 allDone = false; 718 break; 719 } 720 } 721 if (allDone) { 722 // If this was the last child animation to end, then notify listeners that this 723 // AnimatorSet has ended 724 if (mListeners != null) { 725 ArrayList<AnimatorListener> tmpListeners = 726 (ArrayList<AnimatorListener>) mListeners.clone(); 727 int numListeners = tmpListeners.size(); 728 for (int i = 0; i < numListeners; ++i) { 729 tmpListeners.get(i).onAnimationEnd(mAnimatorSet); 730 } 731 } 732 } 733 } 734 } 735 736 // Nothing to do 737 public void onAnimationRepeat(Animator animation) { 738 } 739 740 // Nothing to do 741 public void onAnimationStart(Animator animation) { 742 } 743 744 } 745 746 /** 747 * This method sorts the current set of nodes, if needed. The sort is a simple 748 * DependencyGraph sort, which goes like this: 749 * - All nodes without dependencies become 'roots' 750 * - while roots list is not null 751 * - for each root r 752 * - add r to sorted list 753 * - remove r as a dependency from any other node 754 * - any nodes with no dependencies are added to the roots list 755 */ 756 private void sortNodes() { 757 if (mNeedsSort) { 758 mSortedNodes.clear(); 759 ArrayList<Node> roots = new ArrayList<Node>(); 760 int numNodes = mNodes.size(); 761 for (int i = 0; i < numNodes; ++i) { 762 Node node = mNodes.get(i); 763 if (node.dependencies == null || node.dependencies.size() == 0) { 764 roots.add(node); 765 } 766 } 767 ArrayList<Node> tmpRoots = new ArrayList<Node>(); 768 while (roots.size() > 0) { 769 int numRoots = roots.size(); 770 for (int i = 0; i < numRoots; ++i) { 771 Node root = roots.get(i); 772 mSortedNodes.add(root); 773 if (root.nodeDependents != null) { 774 int numDependents = root.nodeDependents.size(); 775 for (int j = 0; j < numDependents; ++j) { 776 Node node = root.nodeDependents.get(j); 777 node.nodeDependencies.remove(root); 778 if (node.nodeDependencies.size() == 0) { 779 tmpRoots.add(node); 780 } 781 } 782 } 783 } 784 roots.clear(); 785 roots.addAll(tmpRoots); 786 tmpRoots.clear(); 787 } 788 mNeedsSort = false; 789 if (mSortedNodes.size() != mNodes.size()) { 790 throw new IllegalStateException("Circular dependencies cannot exist" 791 + " in AnimatorSet"); 792 } 793 } else { 794 // Doesn't need sorting, but still need to add in the nodeDependencies list 795 // because these get removed as the event listeners fire and the dependencies 796 // are satisfied 797 int numNodes = mNodes.size(); 798 for (int i = 0; i < numNodes; ++i) { 799 Node node = mNodes.get(i); 800 if (node.dependencies != null && node.dependencies.size() > 0) { 801 int numDependencies = node.dependencies.size(); 802 for (int j = 0; j < numDependencies; ++j) { 803 Dependency dependency = node.dependencies.get(j); 804 if (node.nodeDependencies == null) { 805 node.nodeDependencies = new ArrayList<Node>(); 806 } 807 if (!node.nodeDependencies.contains(dependency.node)) { 808 node.nodeDependencies.add(dependency.node); 809 } 810 } 811 } 812 // nodes are 'done' by default; they become un-done when started, and done 813 // again when ended 814 node.done = false; 815 } 816 } 817 } 818 819 /** 820 * Dependency holds information about the node that some other node is 821 * dependent upon and the nature of that dependency. 822 * 823 */ 824 private static class Dependency { 825 static final int WITH = 0; // dependent node must start with this dependency node 826 static final int AFTER = 1; // dependent node must start when this dependency node finishes 827 828 // The node that the other node with this Dependency is dependent upon 829 public Node node; 830 831 // The nature of the dependency (WITH or AFTER) 832 public int rule; 833 834 public Dependency(Node node, int rule) { 835 this.node = node; 836 this.rule = rule; 837 } 838 } 839 840 /** 841 * A Node is an embodiment of both the Animator that it wraps as well as 842 * any dependencies that are associated with that Animation. This includes 843 * both dependencies upon other nodes (in the dependencies list) as 844 * well as dependencies of other nodes upon this (in the nodeDependents list). 845 */ 846 private static class Node implements Cloneable { 847 public Animator animation; 848 849 /** 850 * These are the dependencies that this node's animation has on other 851 * nodes. For example, if this node's animation should begin with some 852 * other animation ends, then there will be an item in this node's 853 * dependencies list for that other animation's node. 854 */ 855 public ArrayList<Dependency> dependencies = null; 856 857 /** 858 * tmpDependencies is a runtime detail. We use the dependencies list for sorting. 859 * But we also use the list to keep track of when multiple dependencies are satisfied, 860 * but removing each dependency as it is satisfied. We do not want to remove 861 * the dependency itself from the list, because we need to retain that information 862 * if the AnimatorSet is launched in the future. So we create a copy of the dependency 863 * list when the AnimatorSet starts and use this tmpDependencies list to track the 864 * list of satisfied dependencies. 865 */ 866 public ArrayList<Dependency> tmpDependencies = null; 867 868 /** 869 * nodeDependencies is just a list of the nodes that this Node is dependent upon. 870 * This information is used in sortNodes(), to determine when a node is a root. 871 */ 872 public ArrayList<Node> nodeDependencies = null; 873 874 /** 875 * nodeDepdendents is the list of nodes that have this node as a dependency. This 876 * is a utility field used in sortNodes to facilitate removing this node as a 877 * dependency when it is a root node. 878 */ 879 public ArrayList<Node> nodeDependents = null; 880 881 /** 882 * Flag indicating whether the animation in this node is finished. This flag 883 * is used by AnimatorSet to check, as each animation ends, whether all child animations 884 * are done and it's time to send out an end event for the entire AnimatorSet. 885 */ 886 public boolean done = false; 887 888 /** 889 * Constructs the Node with the animation that it encapsulates. A Node has no 890 * dependencies by default; dependencies are added via the addDependency() 891 * method. 892 * 893 * @param animation The animation that the Node encapsulates. 894 */ 895 public Node(Animator animation) { 896 this.animation = animation; 897 } 898 899 /** 900 * Add a dependency to this Node. The dependency includes information about the 901 * node that this node is dependency upon and the nature of the dependency. 902 * @param dependency 903 */ 904 public void addDependency(Dependency dependency) { 905 if (dependencies == null) { 906 dependencies = new ArrayList<Dependency>(); 907 nodeDependencies = new ArrayList<Node>(); 908 } 909 dependencies.add(dependency); 910 if (!nodeDependencies.contains(dependency.node)) { 911 nodeDependencies.add(dependency.node); 912 } 913 Node dependencyNode = dependency.node; 914 if (dependencyNode.nodeDependents == null) { 915 dependencyNode.nodeDependents = new ArrayList<Node>(); 916 } 917 dependencyNode.nodeDependents.add(this); 918 } 919 920 @Override 921 public Node clone() { 922 try { 923 Node node = (Node) super.clone(); 924 node.animation = (Animator) animation.clone(); 925 return node; 926 } catch (CloneNotSupportedException e) { 927 throw new AssertionError(); 928 } 929 } 930 } 931 932 /** 933 * The <code>Builder</code> object is a utility class to facilitate adding animations to a 934 * <code>AnimatorSet</code> along with the relationships between the various animations. The 935 * intention of the <code>Builder</code> methods, along with the {@link 936 * AnimatorSet#play(Animator) play()} method of <code>AnimatorSet</code> is to make it possible to 937 * express the dependency relationships of animations in a natural way. Developers can also use 938 * the {@link AnimatorSet#playTogether(Animator[]) playTogether()} and {@link 939 * AnimatorSet#playSequentially(Animator[]) playSequentially()} methods if these suit the need, 940 * but it might be easier in some situations to express the AnimatorSet of animations in pairs. 941 * <p/> 942 * <p>The <code>Builder</code> object cannot be constructed directly, but is rather constructed 943 * internally via a call to {@link AnimatorSet#play(Animator)}.</p> 944 * <p/> 945 * <p>For example, this sets up a AnimatorSet to play anim1 and anim2 at the same time, anim3 to 946 * play when anim2 finishes, and anim4 to play when anim3 finishes:</p> 947 * <pre> 948 * AnimatorSet s = new AnimatorSet(); 949 * s.play(anim1).with(anim2); 950 * s.play(anim2).before(anim3); 951 * s.play(anim4).after(anim3); 952 * </pre> 953 * <p/> 954 * <p>Note in the example that both {@link Builder#before(Animator)} and {@link 955 * Builder#after(Animator)} are used. These are just different ways of expressing the same 956 * relationship and are provided to make it easier to say things in a way that is more natural, 957 * depending on the situation.</p> 958 * <p/> 959 * <p>It is possible to make several calls into the same <code>Builder</code> object to express 960 * multiple relationships. However, note that it is only the animation passed into the initial 961 * {@link AnimatorSet#play(Animator)} method that is the dependency in any of the successive 962 * calls to the <code>Builder</code> object. For example, the following code starts both anim2 963 * and anim3 when anim1 ends; there is no direct dependency relationship between anim2 and 964 * anim3: 965 * <pre> 966 * AnimatorSet s = new AnimatorSet(); 967 * s.play(anim1).before(anim2).before(anim3); 968 * </pre> 969 * If the desired result is to play anim1 then anim2 then anim3, this code expresses the 970 * relationship correctly:</p> 971 * <pre> 972 * AnimatorSet s = new AnimatorSet(); 973 * s.play(anim1).before(anim2); 974 * s.play(anim2).before(anim3); 975 * </pre> 976 * <p/> 977 * <p>Note that it is possible to express relationships that cannot be resolved and will not 978 * result in sensible results. For example, <code>play(anim1).after(anim1)</code> makes no 979 * sense. In general, circular dependencies like this one (or more indirect ones where a depends 980 * on b, which depends on c, which depends on a) should be avoided. Only create AnimatorSets 981 * that can boil down to a simple, one-way relationship of animations starting with, before, and 982 * after other, different, animations.</p> 983 */ 984 public class Builder { 985 986 /** 987 * This tracks the current node being processed. It is supplied to the play() method 988 * of AnimatorSet and passed into the constructor of Builder. 989 */ 990 private Node mCurrentNode; 991 992 /** 993 * package-private constructor. Builders are only constructed by AnimatorSet, when the 994 * play() method is called. 995 * 996 * @param anim The animation that is the dependency for the other animations passed into 997 * the other methods of this Builder object. 998 */ 999 Builder(Animator anim) { 1000 mCurrentNode = mNodeMap.get(anim); 1001 if (mCurrentNode == null) { 1002 mCurrentNode = new Node(anim); 1003 mNodeMap.put(anim, mCurrentNode); 1004 mNodes.add(mCurrentNode); 1005 } 1006 } 1007 1008 /** 1009 * Sets up the given animation to play at the same time as the animation supplied in the 1010 * {@link AnimatorSet#play(Animator)} call that created this <code>Builder</code> object. 1011 * 1012 * @param anim The animation that will play when the animation supplied to the 1013 * {@link AnimatorSet#play(Animator)} method starts. 1014 */ 1015 public Builder with(Animator anim) { 1016 Node node = mNodeMap.get(anim); 1017 if (node == null) { 1018 node = new Node(anim); 1019 mNodeMap.put(anim, node); 1020 mNodes.add(node); 1021 } 1022 Dependency dependency = new Dependency(mCurrentNode, Dependency.WITH); 1023 node.addDependency(dependency); 1024 return this; 1025 } 1026 1027 /** 1028 * Sets up the given animation to play when the animation supplied in the 1029 * {@link AnimatorSet#play(Animator)} call that created this <code>Builder</code> object 1030 * ends. 1031 * 1032 * @param anim The animation that will play when the animation supplied to the 1033 * {@link AnimatorSet#play(Animator)} method ends. 1034 */ 1035 public Builder before(Animator anim) { 1036 Node node = mNodeMap.get(anim); 1037 if (node == null) { 1038 node = new Node(anim); 1039 mNodeMap.put(anim, node); 1040 mNodes.add(node); 1041 } 1042 Dependency dependency = new Dependency(mCurrentNode, Dependency.AFTER); 1043 node.addDependency(dependency); 1044 return this; 1045 } 1046 1047 /** 1048 * Sets up the given animation to play when the animation supplied in the 1049 * {@link AnimatorSet#play(Animator)} call that created this <code>Builder</code> object 1050 * to start when the animation supplied in this method call ends. 1051 * 1052 * @param anim The animation whose end will cause the animation supplied to the 1053 * {@link AnimatorSet#play(Animator)} method to play. 1054 */ 1055 public Builder after(Animator anim) { 1056 Node node = mNodeMap.get(anim); 1057 if (node == null) { 1058 node = new Node(anim); 1059 mNodeMap.put(anim, node); 1060 mNodes.add(node); 1061 } 1062 Dependency dependency = new Dependency(node, Dependency.AFTER); 1063 mCurrentNode.addDependency(dependency); 1064 return this; 1065 } 1066 1067 /** 1068 * Sets up the animation supplied in the 1069 * {@link AnimatorSet#play(Animator)} call that created this <code>Builder</code> object 1070 * to play when the given amount of time elapses. 1071 * 1072 * @param delay The number of milliseconds that should elapse before the 1073 * animation starts. 1074 */ 1075 public Builder after(long delay) { 1076 // setup dummy ValueAnimator just to run the clock 1077 ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f); 1078 anim.setDuration(delay); 1079 after(anim); 1080 return this; 1081 } 1082 1083 } 1084 1085} 1086