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