Transition.java revision f976c3d42bc2f14333bae5ed26d96c45d207a443
1/*
2 * Copyright (C) 2013 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.transition;
18
19import android.animation.Animator;
20import android.animation.AnimatorListenerAdapter;
21import android.animation.TimeInterpolator;
22import android.graphics.Rect;
23import android.util.ArrayMap;
24import android.util.Log;
25import android.util.LongSparseArray;
26import android.util.SparseArray;
27import android.util.SparseLongArray;
28import android.view.SurfaceView;
29import android.view.TextureView;
30import android.view.View;
31import android.view.ViewGroup;
32import android.view.ViewOverlay;
33import android.view.WindowId;
34import android.widget.ListView;
35import android.widget.Spinner;
36
37import java.util.ArrayList;
38import java.util.List;
39
40/**
41 * A Transition holds information about animations that will be run on its
42 * targets during a scene change. Subclasses of this abstract class may
43 * choreograph several child transitions ({@link TransitionSet} or they may
44 * perform custom animations themselves. Any Transition has two main jobs:
45 * (1) capture property values, and (2) play animations based on changes to
46 * captured property values. A custom transition knows what property values
47 * on View objects are of interest to it, and also knows how to animate
48 * changes to those values. For example, the {@link Fade} transition tracks
49 * changes to visibility-related properties and is able to construct and run
50 * animations that fade items in or out based on changes to those properties.
51 *
52 * <p>Note: Transitions may not work correctly with either {@link SurfaceView}
53 * or {@link TextureView}, due to the way that these views are displayed
54 * on the screen. For SurfaceView, the problem is that the view is updated from
55 * a non-UI thread, so changes to the view due to transitions (such as moving
56 * and resizing the view) may be out of sync with the display inside those bounds.
57 * TextureView is more compatible with transitions in general, but some
58 * specific transitions (such as {@link Fade}) may not be compatible
59 * with TextureView because they rely on {@link ViewOverlay} functionality,
60 * which does not currently work with TextureView.</p>
61 *
62 * <p>Transitions can be declared in XML resource files inside the <code>res/transition</code>
63 * directory. Transition resources consist of a tag name for one of the Transition
64 * subclasses along with attributes to define some of the attributes of that transition.
65 * For example, here is a minimal resource file that declares a {@link ChangeBounds} transition:
66 *
67 * {@sample development/samples/ApiDemos/res/transition/changebounds.xml ChangeBounds}
68 *
69 * <p>{@link android.transition.Explode} transition:</p>
70 *
71 * {@sample development/samples/ApiDemos/res/transition/explode.xml Explode}
72 *
73 * <p>{@link android.transition.MoveImage} transition:</p>
74 *
75 * {@sample development/samples/ApiDemos/res/transition/move_image.xml MoveImage}
76 *
77 * <p>Note that attributes for the transition are not required, just as they are
78 * optional when declared in code; Transitions created from XML resources will use
79 * the same defaults as their code-created equivalents. Here is a slightly more
80 * elaborate example which declares a {@link TransitionSet} transition with
81 * {@link ChangeBounds} and {@link Fade} child transitions:</p>
82 *
83 * {@sample
84 * development/samples/ApiDemos/res/transition/changebounds_fadeout_sequential.xml TransitionSet}
85 *
86 * <p>In this example, the transitionOrdering attribute is used on the TransitionSet
87 * object to change from the default {@link TransitionSet#ORDERING_TOGETHER} behavior
88 * to be {@link TransitionSet#ORDERING_SEQUENTIAL} instead. Also, the {@link Fade}
89 * transition uses a fadingMode of {@link Fade#OUT} instead of the default
90 * out-in behavior. Finally, note the use of the <code>targets</code> sub-tag, which
91 * takes a set of {@link android.R.styleable#TransitionTarget target} tags, each
92 * of which lists a specific <code>targetId</code>, <code>excludeId</code>, or
93 * <code>excludeClass</code>, which this transition acts upon.
94 * Use of targets is optional, but can be used to either limit the time spent checking
95 * attributes on unchanging views, or limiting the types of animations run on specific views.
96 * In this case, we know that only the <code>grayscaleContainer</code> will be
97 * disappearing, so we choose to limit the {@link Fade} transition to only that view.</p>
98 *
99 * Further information on XML resource descriptions for transitions can be found for
100 * {@link android.R.styleable#Transition}, {@link android.R.styleable#TransitionSet},
101 * {@link android.R.styleable#TransitionTarget}, {@link android.R.styleable#Fade}, and
102 * {@link android.R.styleable#Slide}.
103 *
104 */
105public abstract class Transition implements Cloneable {
106
107    private static final String LOG_TAG = "Transition";
108    static final boolean DBG = false;
109
110    private String mName = getClass().getName();
111
112    long mStartDelay = -1;
113    long mDuration = -1;
114    TimeInterpolator mInterpolator = null;
115    ArrayList<Integer> mTargetIds = new ArrayList<Integer>();
116    ArrayList<View> mTargets = new ArrayList<View>();
117    ArrayList<Integer> mTargetIdExcludes = null;
118    ArrayList<View> mTargetExcludes = null;
119    ArrayList<Class> mTargetTypeExcludes = null;
120    ArrayList<Integer> mTargetIdChildExcludes = null;
121    ArrayList<View> mTargetChildExcludes = null;
122    ArrayList<Class> mTargetTypeChildExcludes = null;
123    private TransitionValuesMaps mStartValues = new TransitionValuesMaps();
124    private TransitionValuesMaps mEndValues = new TransitionValuesMaps();
125    TransitionSet mParent = null;
126
127    // Per-animator information used for later canceling when future transitions overlap
128    private static ThreadLocal<ArrayMap<Animator, AnimationInfo>> sRunningAnimators =
129            new ThreadLocal<ArrayMap<Animator, AnimationInfo>>();
130
131    // Scene Root is set at createAnimator() time in the cloned Transition
132    ViewGroup mSceneRoot = null;
133
134    // Whether removing views from their parent is possible. This is only for views
135    // in the start scene, which are no longer in the view hierarchy. This property
136    // is determined by whether the previous Scene was created from a layout
137    // resource, and thus the views from the exited scene are going away anyway
138    // and can be removed as necessary to achieve a particular effect, such as
139    // removing them from parents to add them to overlays.
140    boolean mCanRemoveViews = false;
141
142    // Track all animators in use in case the transition gets canceled and needs to
143    // cancel running animators
144    private ArrayList<Animator> mCurrentAnimators = new ArrayList<Animator>();
145
146    // Number of per-target instances of this Transition currently running. This count is
147    // determined by calls to start() and end()
148    int mNumInstances = 0;
149
150    // Whether this transition is currently paused, due to a call to pause()
151    boolean mPaused = false;
152
153    // Whether this transition has ended. Used to avoid pause/resume on transitions
154    // that have completed
155    private boolean mEnded = false;
156
157    // The set of listeners to be sent transition lifecycle events.
158    ArrayList<TransitionListener> mListeners = null;
159
160    // The set of animators collected from calls to createAnimator(),
161    // to be run in runAnimators()
162    ArrayList<Animator> mAnimators = new ArrayList<Animator>();
163
164    // The function for calculating the Animation start delay.
165    TransitionPropagation mPropagation;
166
167    // The rectangular region for Transitions like Explode and TransitionPropagations
168    // like CircularPropagation
169    EpicenterCallback mEpicenterCallback;
170
171    /**
172     * Constructs a Transition object with no target objects. A transition with
173     * no targets defaults to running on all target objects in the scene hierarchy
174     * (if the transition is not contained in a TransitionSet), or all target
175     * objects passed down from its parent (if it is in a TransitionSet).
176     */
177    public Transition() {}
178
179    /**
180     * Sets the duration of this transition. By default, there is no duration
181     * (indicated by a negative number), which means that the Animator created by
182     * the transition will have its own specified duration. If the duration of a
183     * Transition is set, that duration will override the Animator duration.
184     *
185     * @param duration The length of the animation, in milliseconds.
186     * @return This transition object.
187     * @attr ref android.R.styleable#Transition_duration
188     */
189    public Transition setDuration(long duration) {
190        mDuration = duration;
191        return this;
192    }
193
194    /**
195     * Returns the duration set on this transition. If no duration has been set,
196     * the returned value will be negative, indicating that resulting animators will
197     * retain their own durations.
198     *
199     * @return The duration set on this transition, in milliseconds, if one has been
200     * set, otherwise returns a negative number.
201     */
202    public long getDuration() {
203        return mDuration;
204    }
205
206    /**
207     * Sets the startDelay of this transition. By default, there is no delay
208     * (indicated by a negative number), which means that the Animator created by
209     * the transition will have its own specified startDelay. If the delay of a
210     * Transition is set, that delay will override the Animator delay.
211     *
212     * @param startDelay The length of the delay, in milliseconds.
213     * @return This transition object.
214     * @attr ref android.R.styleable#Transition_startDelay
215     */
216    public Transition setStartDelay(long startDelay) {
217        mStartDelay = startDelay;
218        return this;
219    }
220
221    /**
222     * Returns the startDelay set on this transition. If no startDelay has been set,
223     * the returned value will be negative, indicating that resulting animators will
224     * retain their own startDelays.
225     *
226     * @return The startDelay set on this transition, in milliseconds, if one has
227     * been set, otherwise returns a negative number.
228     */
229    public long getStartDelay() {
230        return mStartDelay;
231    }
232
233    /**
234     * Sets the interpolator of this transition. By default, the interpolator
235     * is null, which means that the Animator created by the transition
236     * will have its own specified interpolator. If the interpolator of a
237     * Transition is set, that interpolator will override the Animator interpolator.
238     *
239     * @param interpolator The time interpolator used by the transition
240     * @return This transition object.
241     * @attr ref android.R.styleable#Transition_interpolator
242     */
243    public Transition setInterpolator(TimeInterpolator interpolator) {
244        mInterpolator = interpolator;
245        return this;
246    }
247
248    /**
249     * Returns the interpolator set on this transition. If no interpolator has been set,
250     * the returned value will be null, indicating that resulting animators will
251     * retain their own interpolators.
252     *
253     * @return The interpolator set on this transition, if one has been set, otherwise
254     * returns null.
255     */
256    public TimeInterpolator getInterpolator() {
257        return mInterpolator;
258    }
259
260    /**
261     * Returns the set of property names used stored in the {@link TransitionValues}
262     * object passed into {@link #captureStartValues(TransitionValues)} that
263     * this transition cares about for the purposes of canceling overlapping animations.
264     * When any transition is started on a given scene root, all transitions
265     * currently running on that same scene root are checked to see whether the
266     * properties on which they based their animations agree with the end values of
267     * the same properties in the new transition. If the end values are not equal,
268     * then the old animation is canceled since the new transition will start a new
269     * animation to these new values. If the values are equal, the old animation is
270     * allowed to continue and no new animation is started for that transition.
271     *
272     * <p>A transition does not need to override this method. However, not doing so
273     * will mean that the cancellation logic outlined in the previous paragraph
274     * will be skipped for that transition, possibly leading to artifacts as
275     * old transitions and new transitions on the same targets run in parallel,
276     * animating views toward potentially different end values.</p>
277     *
278     * @return An array of property names as described in the class documentation for
279     * {@link TransitionValues}. The default implementation returns <code>null</code>.
280     */
281    public String[] getTransitionProperties() {
282        return null;
283    }
284
285    /**
286     * This method creates an animation that will be run for this transition
287     * given the information in the startValues and endValues structures captured
288     * earlier for the start and end scenes. Subclasses of Transition should override
289     * this method. The method should only be called by the transition system; it is
290     * not intended to be called from external classes.
291     *
292     * <p>This method is called by the transition's parent (all the way up to the
293     * topmost Transition in the hierarchy) with the sceneRoot and start/end
294     * values that the transition may need to set up initial target values
295     * and construct an appropriate animation. For example, if an overall
296     * Transition is a {@link TransitionSet} consisting of several
297     * child transitions in sequence, then some of the child transitions may
298     * want to set initial values on target views prior to the overall
299     * Transition commencing, to put them in an appropriate state for the
300     * delay between that start and the child Transition start time. For
301     * example, a transition that fades an item in may wish to set the starting
302     * alpha value to 0, to avoid it blinking in prior to the transition
303     * actually starting the animation. This is necessary because the scene
304     * change that triggers the Transition will automatically set the end-scene
305     * on all target views, so a Transition that wants to animate from a
306     * different value should set that value prior to returning from this method.</p>
307     *
308     * <p>Additionally, a Transition can perform logic to determine whether
309     * the transition needs to run on the given target and start/end values.
310     * For example, a transition that resizes objects on the screen may wish
311     * to avoid running for views which are not present in either the start
312     * or end scenes.</p>
313     *
314     * <p>If there is an animator created and returned from this method, the
315     * transition mechanism will apply any applicable duration, startDelay,
316     * and interpolator to that animation and start it. A return value of
317     * <code>null</code> indicates that no animation should run. The default
318     * implementation returns null.</p>
319     *
320     * <p>The method is called for every applicable target object, which is
321     * stored in the {@link TransitionValues#view} field.</p>
322     *
323     *
324     * @param sceneRoot The root of the transition hierarchy.
325     * @param startValues The values for a specific target in the start scene.
326     * @param endValues The values for the target in the end scene.
327     * @return A Animator to be started at the appropriate time in the
328     * overall transition for this scene change. A null value means no animation
329     * should be run.
330     */
331    public Animator createAnimator(ViewGroup sceneRoot, TransitionValues startValues,
332            TransitionValues endValues) {
333        return null;
334    }
335
336    /**
337     * This method, essentially a wrapper around all calls to createAnimator for all
338     * possible target views, is called with the entire set of start/end
339     * values. The implementation in Transition iterates through these lists
340     * and calls {@link #createAnimator(ViewGroup, TransitionValues, TransitionValues)}
341     * with each set of start/end values on this transition. The
342     * TransitionSet subclass overrides this method and delegates it to
343     * each of its children in succession.
344     *
345     * @hide
346     */
347    protected void createAnimators(ViewGroup sceneRoot, TransitionValuesMaps startValues,
348            TransitionValuesMaps endValues) {
349        if (DBG) {
350            Log.d(LOG_TAG, "createAnimators() for " + this);
351        }
352        ArrayMap<View, TransitionValues> endCopy =
353                new ArrayMap<View, TransitionValues>(endValues.viewValues);
354        SparseArray<TransitionValues> endIdCopy =
355                new SparseArray<TransitionValues>(endValues.idValues.size());
356        for (int i = 0; i < endValues.idValues.size(); ++i) {
357            int id = endValues.idValues.keyAt(i);
358            endIdCopy.put(id, endValues.idValues.valueAt(i));
359        }
360        LongSparseArray<TransitionValues> endItemIdCopy =
361                new LongSparseArray<TransitionValues>(endValues.itemIdValues.size());
362        for (int i = 0; i < endValues.itemIdValues.size(); ++i) {
363            long id = endValues.itemIdValues.keyAt(i);
364            endItemIdCopy.put(id, endValues.itemIdValues.valueAt(i));
365        }
366        // Walk through the start values, playing everything we find
367        // Remove from the end set as we go
368        ArrayList<TransitionValues> startValuesList = new ArrayList<TransitionValues>();
369        ArrayList<TransitionValues> endValuesList = new ArrayList<TransitionValues>();
370        for (View view : startValues.viewValues.keySet()) {
371            TransitionValues start = null;
372            TransitionValues end = null;
373            boolean isInListView = false;
374            if (view.getParent() instanceof ListView) {
375                isInListView = true;
376            }
377            if (!isInListView) {
378                int id = view.getId();
379                start = startValues.viewValues.get(view) != null ?
380                        startValues.viewValues.get(view) : startValues.idValues.get(id);
381                if (endValues.viewValues.get(view) != null) {
382                    end = endValues.viewValues.get(view);
383                    endCopy.remove(view);
384                } else if (id != View.NO_ID) {
385                    end = endValues.idValues.get(id);
386                    View removeView = null;
387                    for (View viewToRemove : endCopy.keySet()) {
388                        if (viewToRemove.getId() == id) {
389                            removeView = viewToRemove;
390                        }
391                    }
392                    if (removeView != null) {
393                        endCopy.remove(removeView);
394                    }
395                }
396                endIdCopy.remove(id);
397                if (isValidTarget(view, id)) {
398                    startValuesList.add(start);
399                    endValuesList.add(end);
400                }
401            } else {
402                ListView parent = (ListView) view.getParent();
403                if (parent.getAdapter().hasStableIds()) {
404                    int position = parent.getPositionForView(view);
405                    long itemId = parent.getItemIdAtPosition(position);
406                    start = startValues.itemIdValues.get(itemId);
407                    endItemIdCopy.remove(itemId);
408                    // TODO: deal with targetIDs for itemIDs for ListView items
409                    startValuesList.add(start);
410                    endValuesList.add(end);
411                }
412            }
413        }
414        int startItemIdCopySize = startValues.itemIdValues.size();
415        for (int i = 0; i < startItemIdCopySize; ++i) {
416            long id = startValues.itemIdValues.keyAt(i);
417            if (isValidTarget(null, id)) {
418                TransitionValues start = startValues.itemIdValues.get(id);
419                TransitionValues end = endValues.itemIdValues.get(id);
420                endItemIdCopy.remove(id);
421                startValuesList.add(start);
422                endValuesList.add(end);
423            }
424        }
425        // Now walk through the remains of the end set
426        for (View view : endCopy.keySet()) {
427            int id = view.getId();
428            if (isValidTarget(view, id)) {
429                TransitionValues start = startValues.viewValues.get(view) != null ?
430                        startValues.viewValues.get(view) : startValues.idValues.get(id);
431                TransitionValues end = endCopy.get(view);
432                endIdCopy.remove(id);
433                startValuesList.add(start);
434                endValuesList.add(end);
435            }
436        }
437        int endIdCopySize = endIdCopy.size();
438        for (int i = 0; i < endIdCopySize; ++i) {
439            int id = endIdCopy.keyAt(i);
440            if (isValidTarget(null, id)) {
441                TransitionValues start = startValues.idValues.get(id);
442                TransitionValues end = endIdCopy.get(id);
443                startValuesList.add(start);
444                endValuesList.add(end);
445            }
446        }
447        int endItemIdCopySize = endItemIdCopy.size();
448        for (int i = 0; i < endItemIdCopySize; ++i) {
449            long id = endItemIdCopy.keyAt(i);
450            // TODO: Deal with targetIDs and itemIDs
451            TransitionValues start = startValues.itemIdValues.get(id);
452            TransitionValues end = endItemIdCopy.get(id);
453            startValuesList.add(start);
454            endValuesList.add(end);
455        }
456        ArrayMap<Animator, AnimationInfo> runningAnimators = getRunningAnimators();
457        long minStartDelay = Long.MAX_VALUE;
458        int minAnimator = mAnimators.size();
459        SparseLongArray startDelays = new SparseLongArray();
460        for (int i = 0; i < startValuesList.size(); ++i) {
461            TransitionValues start = startValuesList.get(i);
462            TransitionValues end = endValuesList.get(i);
463            // Only bother trying to animate with values that differ between start/end
464            if (start != null || end != null) {
465                if (start == null || !start.equals(end)) {
466                    if (DBG) {
467                        View view = (end != null) ? end.view : start.view;
468                        Log.d(LOG_TAG, "  differing start/end values for view " +
469                                view);
470                        if (start == null || end == null) {
471                            Log.d(LOG_TAG, "    " + ((start == null) ?
472                                    "start null, end non-null" : "start non-null, end null"));
473                        } else {
474                            for (String key : start.values.keySet()) {
475                                Object startValue = start.values.get(key);
476                                Object endValue = end.values.get(key);
477                                if (startValue != endValue && !startValue.equals(endValue)) {
478                                    Log.d(LOG_TAG, "    " + key + ": start(" + startValue +
479                                            "), end(" + endValue +")");
480                                }
481                            }
482                        }
483                    }
484                    // TODO: what to do about targetIds and itemIds?
485                    Animator animator = createAnimator(sceneRoot, start, end);
486                    if (animator != null) {
487                        // Save animation info for future cancellation purposes
488                        View view = null;
489                        TransitionValues infoValues = null;
490                        if (end != null) {
491                            view = end.view;
492                            String[] properties = getTransitionProperties();
493                            if (view != null && properties != null && properties.length > 0) {
494                                infoValues = new TransitionValues();
495                                infoValues.view = view;
496                                TransitionValues newValues = endValues.viewValues.get(view);
497                                if (newValues != null) {
498                                    for (int j = 0; j < properties.length; ++j) {
499                                        infoValues.values.put(properties[j],
500                                                newValues.values.get(properties[j]));
501                                    }
502                                }
503                                int numExistingAnims = runningAnimators.size();
504                                for (int j = 0; j < numExistingAnims; ++j) {
505                                    Animator anim = runningAnimators.keyAt(j);
506                                    AnimationInfo info = runningAnimators.get(anim);
507                                    if (info.values != null && info.view == view &&
508                                            ((info.name == null && getName() == null) ||
509                                            info.name.equals(getName()))) {
510                                        if (info.values.equals(infoValues)) {
511                                            // Favor the old animator
512                                            animator = null;
513                                            break;
514                                        }
515                                    }
516                                }
517                            }
518                        } else {
519                            view = (start != null) ? start.view : null;
520                        }
521                        if (animator != null) {
522                            if (mPropagation != null) {
523                                long delay = mPropagation
524                                        .getStartDelay(sceneRoot, this, start, end);
525                                startDelays.put(mAnimators.size(), delay);
526                                minStartDelay = Math.min(delay, minStartDelay);
527                            }
528                            AnimationInfo info = new AnimationInfo(view, getName(),
529                                    sceneRoot.getWindowId(), infoValues);
530                            runningAnimators.put(animator, info);
531                            mAnimators.add(animator);
532                        }
533                    }
534                }
535            }
536        }
537        if (minStartDelay != 0) {
538            for (int i = 0; i < startDelays.size(); i++) {
539                int index = startDelays.keyAt(i);
540                Animator animator = mAnimators.get(index);
541                long delay = startDelays.valueAt(i) - minStartDelay + animator.getStartDelay();
542                animator.setStartDelay(delay);
543            }
544        }
545    }
546
547    /**
548     * Internal utility method for checking whether a given view/id
549     * is valid for this transition, where "valid" means that either
550     * the Transition has no target/targetId list (the default, in which
551     * cause the transition should act on all views in the hiearchy), or
552     * the given view is in the target list or the view id is in the
553     * targetId list. If the target parameter is null, then the target list
554     * is not checked (this is in the case of ListView items, where the
555     * views are ignored and only the ids are used).
556     */
557    boolean isValidTarget(View target, long targetId) {
558        if (mTargetIdExcludes != null && mTargetIdExcludes.contains(targetId)) {
559            return false;
560        }
561        if (mTargetExcludes != null && mTargetExcludes.contains(target)) {
562            return false;
563        }
564        if (mTargetTypeExcludes != null && target != null) {
565            int numTypes = mTargetTypeExcludes.size();
566            for (int i = 0; i < numTypes; ++i) {
567                Class type = mTargetTypeExcludes.get(i);
568                if (type.isInstance(target)) {
569                    return false;
570                }
571            }
572        }
573        if (mTargetIds.size() == 0 && mTargets.size() == 0) {
574            return true;
575        }
576        if (mTargetIds.size() > 0) {
577            for (int i = 0; i < mTargetIds.size(); ++i) {
578                if (mTargetIds.get(i) == targetId) {
579                    return true;
580                }
581            }
582        }
583        if (target != null && mTargets.size() > 0) {
584            for (int i = 0; i < mTargets.size(); ++i) {
585                if (mTargets.get(i) == target) {
586                    return true;
587                }
588            }
589        }
590        return false;
591    }
592
593    private static ArrayMap<Animator, AnimationInfo> getRunningAnimators() {
594        ArrayMap<Animator, AnimationInfo> runningAnimators = sRunningAnimators.get();
595        if (runningAnimators == null) {
596            runningAnimators = new ArrayMap<Animator, AnimationInfo>();
597            sRunningAnimators.set(runningAnimators);
598        }
599        return runningAnimators;
600    }
601
602    /**
603     * This is called internally once all animations have been set up by the
604     * transition hierarchy.
605     *
606     * @hide
607     */
608    protected void runAnimators() {
609        if (DBG) {
610            Log.d(LOG_TAG, "runAnimators() on " + this);
611        }
612        start();
613        ArrayMap<Animator, AnimationInfo> runningAnimators = getRunningAnimators();
614        // Now start every Animator that was previously created for this transition
615        for (Animator anim : mAnimators) {
616            if (DBG) {
617                Log.d(LOG_TAG, "  anim: " + anim);
618            }
619            if (runningAnimators.containsKey(anim)) {
620                start();
621                runAnimator(anim, runningAnimators);
622            }
623        }
624        mAnimators.clear();
625        end();
626    }
627
628    private void runAnimator(Animator animator,
629            final ArrayMap<Animator, AnimationInfo> runningAnimators) {
630        if (animator != null) {
631            // TODO: could be a single listener instance for all of them since it uses the param
632            animator.addListener(new AnimatorListenerAdapter() {
633                @Override
634                public void onAnimationStart(Animator animation) {
635                    mCurrentAnimators.add(animation);
636                }
637                @Override
638                public void onAnimationEnd(Animator animation) {
639                    runningAnimators.remove(animation);
640                    mCurrentAnimators.remove(animation);
641                }
642            });
643            animate(animator);
644        }
645    }
646
647    /**
648     * Captures the values in the start scene for the properties that this
649     * transition monitors. These values are then passed as the startValues
650     * structure in a later call to
651     * {@link #createAnimator(ViewGroup, TransitionValues, TransitionValues)}.
652     * The main concern for an implementation is what the
653     * properties are that the transition cares about and what the values are
654     * for all of those properties. The start and end values will be compared
655     * later during the
656     * {@link #createAnimator(android.view.ViewGroup, TransitionValues, TransitionValues)}
657     * method to determine what, if any, animations, should be run.
658     *
659     * <p>Subclasses must implement this method. The method should only be called by the
660     * transition system; it is not intended to be called from external classes.</p>
661     *
662     * @param transitionValues The holder for any values that the Transition
663     * wishes to store. Values are stored in the <code>values</code> field
664     * of this TransitionValues object and are keyed from
665     * a String value. For example, to store a view's rotation value,
666     * a transition might call
667     * <code>transitionValues.values.put("appname:transitionname:rotation",
668     * view.getRotation())</code>. The target view will already be stored in
669     * the transitionValues structure when this method is called.
670     *
671     * @see #captureEndValues(TransitionValues)
672     * @see #createAnimator(ViewGroup, TransitionValues, TransitionValues)
673     */
674    public abstract void captureStartValues(TransitionValues transitionValues);
675
676    /**
677     * Captures the values in the end scene for the properties that this
678     * transition monitors. These values are then passed as the endValues
679     * structure in a later call to
680     * {@link #createAnimator(ViewGroup, TransitionValues, TransitionValues)}.
681     * The main concern for an implementation is what the
682     * properties are that the transition cares about and what the values are
683     * for all of those properties. The start and end values will be compared
684     * later during the
685     * {@link #createAnimator(android.view.ViewGroup, TransitionValues, TransitionValues)}
686     * method to determine what, if any, animations, should be run.
687     *
688     * <p>Subclasses must implement this method. The method should only be called by the
689     * transition system; it is not intended to be called from external classes.</p>
690     *
691     * @param transitionValues The holder for any values that the Transition
692     * wishes to store. Values are stored in the <code>values</code> field
693     * of this TransitionValues object and are keyed from
694     * a String value. For example, to store a view's rotation value,
695     * a transition might call
696     * <code>transitionValues.values.put("appname:transitionname:rotation",
697     * view.getRotation())</code>. The target view will already be stored in
698     * the transitionValues structure when this method is called.
699     *
700     * @see #captureStartValues(TransitionValues)
701     * @see #createAnimator(ViewGroup, TransitionValues, TransitionValues)
702     */
703    public abstract void captureEndValues(TransitionValues transitionValues);
704
705    /**
706     * Adds the id of a target view that this Transition is interested in
707     * animating. By default, there are no targetIds, and a Transition will
708     * listen for changes on every view in the hierarchy below the sceneRoot
709     * of the Scene being transitioned into. Setting targetIds constrains
710     * the Transition to only listen for, and act on, views with these IDs.
711     * Views with different IDs, or no IDs whatsoever, will be ignored.
712     *
713     * <p>Note that using ids to specify targets implies that ids should be unique
714     * within the view hierarchy underneat the scene root.</p>
715     *
716     * @see View#getId()
717     * @param targetId The id of a target view, must be a positive number.
718     * @return The Transition to which the targetId is added.
719     * Returning the same object makes it easier to chain calls during
720     * construction, such as
721     * <code>transitionSet.addTransitions(new Fade()).addTarget(someId);</code>
722     */
723    public Transition addTarget(int targetId) {
724        if (targetId > 0) {
725            mTargetIds.add(targetId);
726        }
727        return this;
728    }
729
730    /**
731     * Removes the given targetId from the list of ids that this Transition
732     * is interested in animating.
733     *
734     * @param targetId The id of a target view, must be a positive number.
735     * @return The Transition from which the targetId is removed.
736     * Returning the same object makes it easier to chain calls during
737     * construction, such as
738     * <code>transitionSet.addTransitions(new Fade()).removeTargetId(someId);</code>
739     */
740    public Transition removeTarget(int targetId) {
741        if (targetId > 0) {
742            mTargetIds.remove(targetId);
743        }
744        return this;
745    }
746
747    /**
748     * Whether to add the given id to the list of target ids to exclude from this
749     * transition. The <code>exclude</code> parameter specifies whether the target
750     * should be added to or removed from the excluded list.
751     *
752     * <p>Excluding targets is a general mechanism for allowing transitions to run on
753     * a view hierarchy while skipping target views that should not be part of
754     * the transition. For example, you may want to avoid animating children
755     * of a specific ListView or Spinner. Views can be excluded either by their
756     * id, or by their instance reference, or by the Class of that view
757     * (eg, {@link Spinner}).</p>
758     *
759     * @see #excludeChildren(int, boolean)
760     * @see #excludeTarget(View, boolean)
761     * @see #excludeTarget(Class, boolean)
762     *
763     * @param targetId The id of a target to ignore when running this transition.
764     * @param exclude Whether to add the target to or remove the target from the
765     * current list of excluded targets.
766     * @return This transition object.
767     */
768    public Transition excludeTarget(int targetId, boolean exclude) {
769        mTargetIdExcludes = excludeId(mTargetIdExcludes, targetId, exclude);
770        return this;
771    }
772
773    /**
774     * Whether to add the children of the given id to the list of targets to exclude
775     * from this transition. The <code>exclude</code> parameter specifies whether
776     * the children of the target should be added to or removed from the excluded list.
777     * Excluding children in this way provides a simple mechanism for excluding all
778     * children of specific targets, rather than individually excluding each
779     * child individually.
780     *
781     * <p>Excluding targets is a general mechanism for allowing transitions to run on
782     * a view hierarchy while skipping target views that should not be part of
783     * the transition. For example, you may want to avoid animating children
784     * of a specific ListView or Spinner. Views can be excluded either by their
785     * id, or by their instance reference, or by the Class of that view
786     * (eg, {@link Spinner}).</p>
787     *
788     * @see #excludeTarget(int, boolean)
789     * @see #excludeChildren(View, boolean)
790     * @see #excludeChildren(Class, boolean)
791     *
792     * @param targetId The id of a target whose children should be ignored when running
793     * this transition.
794     * @param exclude Whether to add the target to or remove the target from the
795     * current list of excluded-child targets.
796     * @return This transition object.
797     */
798    public Transition excludeChildren(int targetId, boolean exclude) {
799        mTargetIdChildExcludes = excludeId(mTargetIdChildExcludes, targetId, exclude);
800        return this;
801    }
802
803    /**
804     * Utility method to manage the boilerplate code that is the same whether we
805     * are excluding targets or their children.
806     */
807    private ArrayList<Integer> excludeId(ArrayList<Integer> list, int targetId, boolean exclude) {
808        if (targetId > 0) {
809            if (exclude) {
810                list = ArrayListManager.add(list, targetId);
811            } else {
812                list = ArrayListManager.remove(list, targetId);
813            }
814        }
815        return list;
816    }
817
818    /**
819     * Whether to add the given target to the list of targets to exclude from this
820     * transition. The <code>exclude</code> parameter specifies whether the target
821     * should be added to or removed from the excluded list.
822     *
823     * <p>Excluding targets is a general mechanism for allowing transitions to run on
824     * a view hierarchy while skipping target views that should not be part of
825     * the transition. For example, you may want to avoid animating children
826     * of a specific ListView or Spinner. Views can be excluded either by their
827     * id, or by their instance reference, or by the Class of that view
828     * (eg, {@link Spinner}).</p>
829     *
830     * @see #excludeChildren(View, boolean)
831     * @see #excludeTarget(int, boolean)
832     * @see #excludeTarget(Class, boolean)
833     *
834     * @param target The target to ignore when running this transition.
835     * @param exclude Whether to add the target to or remove the target from the
836     * current list of excluded targets.
837     * @return This transition object.
838     */
839    public Transition excludeTarget(View target, boolean exclude) {
840        mTargetExcludes = excludeView(mTargetExcludes, target, exclude);
841        return this;
842    }
843
844    /**
845     * Whether to add the children of given target to the list of target children
846     * to exclude from this transition. The <code>exclude</code> parameter specifies
847     * whether the target should be added to or removed from the excluded list.
848     *
849     * <p>Excluding targets is a general mechanism for allowing transitions to run on
850     * a view hierarchy while skipping target views that should not be part of
851     * the transition. For example, you may want to avoid animating children
852     * of a specific ListView or Spinner. Views can be excluded either by their
853     * id, or by their instance reference, or by the Class of that view
854     * (eg, {@link Spinner}).</p>
855     *
856     * @see #excludeTarget(View, boolean)
857     * @see #excludeChildren(int, boolean)
858     * @see #excludeChildren(Class, boolean)
859     *
860     * @param target The target to ignore when running this transition.
861     * @param exclude Whether to add the target to or remove the target from the
862     * current list of excluded targets.
863     * @return This transition object.
864     */
865    public Transition excludeChildren(View target, boolean exclude) {
866        mTargetChildExcludes = excludeView(mTargetChildExcludes, target, exclude);
867        return this;
868    }
869
870    /**
871     * Utility method to manage the boilerplate code that is the same whether we
872     * are excluding targets or their children.
873     */
874    private ArrayList<View> excludeView(ArrayList<View> list, View target, boolean exclude) {
875        if (target != null) {
876            if (exclude) {
877                list = ArrayListManager.add(list, target);
878            } else {
879                list = ArrayListManager.remove(list, target);
880            }
881        }
882        return list;
883    }
884
885    /**
886     * Whether to add the given type to the list of types to exclude from this
887     * transition. The <code>exclude</code> parameter specifies whether the target
888     * type should be added to or removed from the excluded list.
889     *
890     * <p>Excluding targets is a general mechanism for allowing transitions to run on
891     * a view hierarchy while skipping target views that should not be part of
892     * the transition. For example, you may want to avoid animating children
893     * of a specific ListView or Spinner. Views can be excluded either by their
894     * id, or by their instance reference, or by the Class of that view
895     * (eg, {@link Spinner}).</p>
896     *
897     * @see #excludeChildren(Class, boolean)
898     * @see #excludeTarget(int, boolean)
899     * @see #excludeTarget(View, boolean)
900     *
901     * @param type The type to ignore when running this transition.
902     * @param exclude Whether to add the target type to or remove it from the
903     * current list of excluded target types.
904     * @return This transition object.
905     */
906    public Transition excludeTarget(Class type, boolean exclude) {
907        mTargetTypeExcludes = excludeType(mTargetTypeExcludes, type, exclude);
908        return this;
909    }
910
911    /**
912     * Whether to add the given type to the list of types whose children should
913     * be excluded from this transition. The <code>exclude</code> parameter
914     * specifies whether the target type should be added to or removed from
915     * the excluded list.
916     *
917     * <p>Excluding targets is a general mechanism for allowing transitions to run on
918     * a view hierarchy while skipping target views that should not be part of
919     * the transition. For example, you may want to avoid animating children
920     * of a specific ListView or Spinner. Views can be excluded either by their
921     * id, or by their instance reference, or by the Class of that view
922     * (eg, {@link Spinner}).</p>
923     *
924     * @see #excludeTarget(Class, boolean)
925     * @see #excludeChildren(int, boolean)
926     * @see #excludeChildren(View, boolean)
927     *
928     * @param type The type to ignore when running this transition.
929     * @param exclude Whether to add the target type to or remove it from the
930     * current list of excluded target types.
931     * @return This transition object.
932     */
933    public Transition excludeChildren(Class type, boolean exclude) {
934        mTargetTypeChildExcludes = excludeType(mTargetTypeChildExcludes, type, exclude);
935        return this;
936    }
937
938    /**
939     * Utility method to manage the boilerplate code that is the same whether we
940     * are excluding targets or their children.
941     */
942    private ArrayList<Class> excludeType(ArrayList<Class> list, Class type, boolean exclude) {
943        if (type != null) {
944            if (exclude) {
945                list = ArrayListManager.add(list, type);
946            } else {
947                list = ArrayListManager.remove(list, type);
948            }
949        }
950        return list;
951    }
952
953    /**
954     * Sets the target view instances that this Transition is interested in
955     * animating. By default, there are no targets, and a Transition will
956     * listen for changes on every view in the hierarchy below the sceneRoot
957     * of the Scene being transitioned into. Setting targets constrains
958     * the Transition to only listen for, and act on, these views.
959     * All other views will be ignored.
960     *
961     * <p>The target list is like the {@link #addTarget(int) targetId}
962     * list except this list specifies the actual View instances, not the ids
963     * of the views. This is an important distinction when scene changes involve
964     * view hierarchies which have been inflated separately; different views may
965     * share the same id but not actually be the same instance. If the transition
966     * should treat those views as the same, then {@link #addTarget(int)} should be used
967     * instead of {@link #addTarget(View)}. If, on the other hand, scene changes involve
968     * changes all within the same view hierarchy, among views which do not
969     * necessarily have ids set on them, then the target list of views may be more
970     * convenient.</p>
971     *
972     * @see #addTarget(int)
973     * @param target A View on which the Transition will act, must be non-null.
974     * @return The Transition to which the target is added.
975     * Returning the same object makes it easier to chain calls during
976     * construction, such as
977     * <code>transitionSet.addTransitions(new Fade()).addTarget(someView);</code>
978     */
979    public Transition addTarget(View target) {
980        mTargets.add(target);
981        return this;
982    }
983
984    /**
985     * Removes the given target from the list of targets that this Transition
986     * is interested in animating.
987     *
988     * @param target The target view, must be non-null.
989     * @return Transition The Transition from which the target is removed.
990     * Returning the same object makes it easier to chain calls during
991     * construction, such as
992     * <code>transitionSet.addTransitions(new Fade()).removeTarget(someView);</code>
993     */
994    public Transition removeTarget(View target) {
995        if (target != null) {
996            mTargets.remove(target);
997        }
998        return this;
999    }
1000
1001    /**
1002     * Returns the array of target IDs that this transition limits itself to
1003     * tracking and animating. If the array is null for both this method and
1004     * {@link #getTargets()}, then this transition is
1005     * not limited to specific views, and will handle changes to any views
1006     * in the hierarchy of a scene change.
1007     *
1008     * @return the list of target IDs
1009     */
1010    public List<Integer> getTargetIds() {
1011        return mTargetIds;
1012    }
1013
1014    /**
1015     * Returns the array of target views that this transition limits itself to
1016     * tracking and animating. If the array is null for both this method and
1017     * {@link #getTargetIds()}, then this transition is
1018     * not limited to specific views, and will handle changes to any views
1019     * in the hierarchy of a scene change.
1020     *
1021     * @return the list of target views
1022     */
1023    public List<View> getTargets() {
1024        return mTargets;
1025    }
1026
1027    /**
1028     * Recursive method that captures values for the given view and the
1029     * hierarchy underneath it.
1030     * @param sceneRoot The root of the view hierarchy being captured
1031     * @param start true if this capture is happening before the scene change,
1032     * false otherwise
1033     */
1034    void captureValues(ViewGroup sceneRoot, boolean start) {
1035        clearValues(start);
1036        if (mTargetIds.size() > 0 || mTargets.size() > 0) {
1037            if (mTargetIds.size() > 0) {
1038                for (int i = 0; i < mTargetIds.size(); ++i) {
1039                    int id = mTargetIds.get(i);
1040                    View view = sceneRoot.findViewById(id);
1041                    if (view != null) {
1042                        TransitionValues values = new TransitionValues();
1043                        values.view = view;
1044                        if (start) {
1045                            captureStartValues(values);
1046                        } else {
1047                            captureEndValues(values);
1048                        }
1049                        capturePropagationValues(values);
1050                        if (start) {
1051                            mStartValues.viewValues.put(view, values);
1052                            if (id >= 0) {
1053                                mStartValues.idValues.put(id, values);
1054                            }
1055                        } else {
1056                            mEndValues.viewValues.put(view, values);
1057                            if (id >= 0) {
1058                                mEndValues.idValues.put(id, values);
1059                            }
1060                        }
1061                    }
1062                }
1063            }
1064            if (mTargets.size() > 0) {
1065                for (int i = 0; i < mTargets.size(); ++i) {
1066                    View view = mTargets.get(i);
1067                    if (view != null) {
1068                        TransitionValues values = new TransitionValues();
1069                        values.view = view;
1070                        if (start) {
1071                            captureStartValues(values);
1072                        } else {
1073                            captureEndValues(values);
1074                        }
1075                        capturePropagationValues(values);
1076                        if (start) {
1077                            mStartValues.viewValues.put(view, values);
1078                        } else {
1079                            mEndValues.viewValues.put(view, values);
1080                        }
1081                    }
1082                }
1083            }
1084        } else {
1085            captureHierarchy(sceneRoot, start);
1086        }
1087    }
1088
1089    /**
1090     * Clear valuesMaps for specified start/end state
1091     *
1092     * @param start true if the start values should be cleared, false otherwise
1093     */
1094    void clearValues(boolean start) {
1095        if (start) {
1096            mStartValues.viewValues.clear();
1097            mStartValues.idValues.clear();
1098            mStartValues.itemIdValues.clear();
1099        } else {
1100            mEndValues.viewValues.clear();
1101            mEndValues.idValues.clear();
1102            mEndValues.itemIdValues.clear();
1103        }
1104    }
1105
1106    /**
1107     * Recursive method which captures values for an entire view hierarchy,
1108     * starting at some root view. Transitions without targetIDs will use this
1109     * method to capture values for all possible views.
1110     *
1111     * @param view The view for which to capture values. Children of this View
1112     * will also be captured, recursively down to the leaf nodes.
1113     * @param start true if values are being captured in the start scene, false
1114     * otherwise.
1115     */
1116    private void captureHierarchy(View view, boolean start) {
1117        if (view == null) {
1118            return;
1119        }
1120        if (!isValidTarget(view, view.getId())) {
1121            return;
1122        }
1123        boolean isListViewItem = false;
1124        if (view.getParent() instanceof ListView) {
1125            isListViewItem = true;
1126        }
1127        if (isListViewItem && !((ListView) view.getParent()).getAdapter().hasStableIds()) {
1128            // ignore listview children unless we can track them with stable IDs
1129            return;
1130        }
1131        int id = View.NO_ID;
1132        long itemId = View.NO_ID;
1133        if (!isListViewItem) {
1134            id = view.getId();
1135        } else {
1136            ListView listview = (ListView) view.getParent();
1137            int position = listview.getPositionForView(view);
1138            itemId = listview.getItemIdAtPosition(position);
1139            view.setHasTransientState(true);
1140        }
1141        if (mTargetIdExcludes != null && mTargetIdExcludes.contains(id)) {
1142            return;
1143        }
1144        if (mTargetExcludes != null && mTargetExcludes.contains(view)) {
1145            return;
1146        }
1147        if (mTargetTypeExcludes != null && view != null) {
1148            int numTypes = mTargetTypeExcludes.size();
1149            for (int i = 0; i < numTypes; ++i) {
1150                if (mTargetTypeExcludes.get(i).isInstance(view)) {
1151                    return;
1152                }
1153            }
1154        }
1155        if (view.getParent() instanceof ViewGroup) {
1156            TransitionValues values = new TransitionValues();
1157            values.view = view;
1158            if (start) {
1159                captureStartValues(values);
1160            } else {
1161                captureEndValues(values);
1162            }
1163            capturePropagationValues(values);
1164            if (start) {
1165                if (!isListViewItem) {
1166                    mStartValues.viewValues.put(view, values);
1167                    if (id >= 0) {
1168                        mStartValues.idValues.put((int) id, values);
1169                    }
1170                } else {
1171                    mStartValues.itemIdValues.put(itemId, values);
1172                }
1173            } else {
1174                if (!isListViewItem) {
1175                    mEndValues.viewValues.put(view, values);
1176                    if (id >= 0) {
1177                        mEndValues.idValues.put((int) id, values);
1178                    }
1179                } else {
1180                    mEndValues.itemIdValues.put(itemId, values);
1181                }
1182            }
1183        }
1184        if (view instanceof ViewGroup) {
1185            // Don't traverse child hierarchy if there are any child-excludes on this view
1186            if (mTargetIdChildExcludes != null && mTargetIdChildExcludes.contains(id)) {
1187                return;
1188            }
1189            if (mTargetChildExcludes != null && mTargetChildExcludes.contains(view)) {
1190                return;
1191            }
1192            if (mTargetTypeChildExcludes != null && view != null) {
1193                int numTypes = mTargetTypeChildExcludes.size();
1194                for (int i = 0; i < numTypes; ++i) {
1195                    if (mTargetTypeChildExcludes.get(i).isInstance(view)) {
1196                        return;
1197                    }
1198                }
1199            }
1200            ViewGroup parent = (ViewGroup) view;
1201            for (int i = 0; i < parent.getChildCount(); ++i) {
1202                captureHierarchy(parent.getChildAt(i), start);
1203            }
1204        }
1205    }
1206
1207    /**
1208     * This method can be called by transitions to get the TransitionValues for
1209     * any particular view during the transition-playing process. This might be
1210     * necessary, for example, to query the before/after state of related views
1211     * for a given transition.
1212     */
1213    public TransitionValues getTransitionValues(View view, boolean start) {
1214        if (mParent != null) {
1215            return mParent.getTransitionValues(view, start);
1216        }
1217        TransitionValuesMaps valuesMaps = start ? mStartValues : mEndValues;
1218        TransitionValues values = valuesMaps.viewValues.get(view);
1219        if (values == null) {
1220            int id = view.getId();
1221            if (id >= 0) {
1222                values = valuesMaps.idValues.get(id);
1223            }
1224            if (values == null && view.getParent() instanceof ListView) {
1225                ListView listview = (ListView) view.getParent();
1226                int position = listview.getPositionForView(view);
1227                long itemId = listview.getItemIdAtPosition(position);
1228                values = valuesMaps.itemIdValues.get(itemId);
1229            }
1230            // TODO: Doesn't handle the case where a view was parented to a
1231            // ListView (with an itemId), but no longer is
1232        }
1233        return values;
1234    }
1235
1236    /**
1237     * Pauses this transition, sending out calls to {@link
1238     * TransitionListener#onTransitionPause(Transition)} to all listeners
1239     * and pausing all running animators started by this transition.
1240     *
1241     * @hide
1242     */
1243    public void pause(View sceneRoot) {
1244        if (!mEnded) {
1245            ArrayMap<Animator, AnimationInfo> runningAnimators = getRunningAnimators();
1246            int numOldAnims = runningAnimators.size();
1247            WindowId windowId = sceneRoot.getWindowId();
1248            for (int i = numOldAnims - 1; i >= 0; i--) {
1249                AnimationInfo info = runningAnimators.valueAt(i);
1250                if (info.view != null && windowId.equals(info.windowId)) {
1251                    Animator anim = runningAnimators.keyAt(i);
1252                    anim.pause();
1253                }
1254            }
1255            if (mListeners != null && mListeners.size() > 0) {
1256                ArrayList<TransitionListener> tmpListeners =
1257                        (ArrayList<TransitionListener>) mListeners.clone();
1258                int numListeners = tmpListeners.size();
1259                for (int i = 0; i < numListeners; ++i) {
1260                    tmpListeners.get(i).onTransitionPause(this);
1261                }
1262            }
1263            mPaused = true;
1264        }
1265    }
1266
1267    /**
1268     * Resumes this transition, sending out calls to {@link
1269     * TransitionListener#onTransitionPause(Transition)} to all listeners
1270     * and pausing all running animators started by this transition.
1271     *
1272     * @hide
1273     */
1274    public void resume(View sceneRoot) {
1275        if (mPaused) {
1276            if (!mEnded) {
1277                ArrayMap<Animator, AnimationInfo> runningAnimators = getRunningAnimators();
1278                int numOldAnims = runningAnimators.size();
1279                WindowId windowId = sceneRoot.getWindowId();
1280                for (int i = numOldAnims - 1; i >= 0; i--) {
1281                    AnimationInfo info = runningAnimators.valueAt(i);
1282                    if (info.view != null && windowId.equals(info.windowId)) {
1283                        Animator anim = runningAnimators.keyAt(i);
1284                        anim.resume();
1285                    }
1286                }
1287                if (mListeners != null && mListeners.size() > 0) {
1288                    ArrayList<TransitionListener> tmpListeners =
1289                            (ArrayList<TransitionListener>) mListeners.clone();
1290                    int numListeners = tmpListeners.size();
1291                    for (int i = 0; i < numListeners; ++i) {
1292                        tmpListeners.get(i).onTransitionResume(this);
1293                    }
1294                }
1295            }
1296            mPaused = false;
1297        }
1298    }
1299
1300    /**
1301     * Called by TransitionManager to play the transition. This calls
1302     * createAnimators() to set things up and create all of the animations and then
1303     * runAnimations() to actually start the animations.
1304     */
1305    void playTransition(ViewGroup sceneRoot) {
1306        ArrayMap<Animator, AnimationInfo> runningAnimators = getRunningAnimators();
1307        int numOldAnims = runningAnimators.size();
1308        for (int i = numOldAnims - 1; i >= 0; i--) {
1309            Animator anim = runningAnimators.keyAt(i);
1310            if (anim != null) {
1311                AnimationInfo oldInfo = runningAnimators.get(anim);
1312                if (oldInfo != null && oldInfo.view != null &&
1313                        oldInfo.view.getContext() == sceneRoot.getContext()) {
1314                    boolean cancel = false;
1315                    TransitionValues oldValues = oldInfo.values;
1316                    View oldView = oldInfo.view;
1317                    TransitionValues newValues = mEndValues.viewValues != null ?
1318                            mEndValues.viewValues.get(oldView) : null;
1319                    if (newValues == null) {
1320                        newValues = mEndValues.idValues.get(oldView.getId());
1321                    }
1322                    if (oldValues != null) {
1323                        // if oldValues null, then transition didn't care to stash values,
1324                        // and won't get canceled
1325                        if (newValues != null) {
1326                            for (String key : oldValues.values.keySet()) {
1327                                Object oldValue = oldValues.values.get(key);
1328                                Object newValue = newValues.values.get(key);
1329                                if (oldValue != null && newValue != null &&
1330                                        !oldValue.equals(newValue)) {
1331                                    cancel = true;
1332                                    if (DBG) {
1333                                        Log.d(LOG_TAG, "Transition.playTransition: " +
1334                                                "oldValue != newValue for " + key +
1335                                                ": old, new = " + oldValue + ", " + newValue);
1336                                    }
1337                                    break;
1338                                }
1339                            }
1340                        }
1341                    }
1342                    if (cancel) {
1343                        if (anim.isRunning() || anim.isStarted()) {
1344                            if (DBG) {
1345                                Log.d(LOG_TAG, "Canceling anim " + anim);
1346                            }
1347                            anim.cancel();
1348                        } else {
1349                            if (DBG) {
1350                                Log.d(LOG_TAG, "removing anim from info list: " + anim);
1351                            }
1352                            runningAnimators.remove(anim);
1353                        }
1354                    }
1355                }
1356            }
1357        }
1358
1359        createAnimators(sceneRoot, mStartValues, mEndValues);
1360        runAnimators();
1361    }
1362
1363    /**
1364     * This is a utility method used by subclasses to handle standard parts of
1365     * setting up and running an Animator: it sets the {@link #getDuration()
1366     * duration} and the {@link #getStartDelay() startDelay}, starts the
1367     * animation, and, when the animator ends, calls {@link #end()}.
1368     *
1369     * @param animator The Animator to be run during this transition.
1370     *
1371     * @hide
1372     */
1373    protected void animate(Animator animator) {
1374        // TODO: maybe pass auto-end as a boolean parameter?
1375        if (animator == null) {
1376            end();
1377        } else {
1378            if (getDuration() >= 0) {
1379                animator.setDuration(getDuration());
1380            }
1381            if (getStartDelay() >= 0) {
1382                animator.setStartDelay(getStartDelay() + animator.getStartDelay());
1383            }
1384            if (getInterpolator() != null) {
1385                animator.setInterpolator(getInterpolator());
1386            }
1387            animator.addListener(new AnimatorListenerAdapter() {
1388                @Override
1389                public void onAnimationEnd(Animator animation) {
1390                    end();
1391                    animation.removeListener(this);
1392                }
1393            });
1394            animator.start();
1395        }
1396    }
1397
1398    /**
1399     * This method is called automatically by the transition and
1400     * TransitionSet classes prior to a Transition subclass starting;
1401     * subclasses should not need to call it directly.
1402     *
1403     * @hide
1404     */
1405    protected void start() {
1406        if (mNumInstances == 0) {
1407            if (mListeners != null && mListeners.size() > 0) {
1408                ArrayList<TransitionListener> tmpListeners =
1409                        (ArrayList<TransitionListener>) mListeners.clone();
1410                int numListeners = tmpListeners.size();
1411                for (int i = 0; i < numListeners; ++i) {
1412                    tmpListeners.get(i).onTransitionStart(this);
1413                }
1414            }
1415            mEnded = false;
1416        }
1417        mNumInstances++;
1418    }
1419
1420    /**
1421     * This method is called automatically by the Transition and
1422     * TransitionSet classes when a transition finishes, either because
1423     * a transition did nothing (returned a null Animator from
1424     * {@link Transition#createAnimator(ViewGroup, TransitionValues,
1425     * TransitionValues)}) or because the transition returned a valid
1426     * Animator and end() was called in the onAnimationEnd()
1427     * callback of the AnimatorListener.
1428     *
1429     * @hide
1430     */
1431    protected void end() {
1432        --mNumInstances;
1433        if (mNumInstances == 0) {
1434            if (mListeners != null && mListeners.size() > 0) {
1435                ArrayList<TransitionListener> tmpListeners =
1436                        (ArrayList<TransitionListener>) mListeners.clone();
1437                int numListeners = tmpListeners.size();
1438                for (int i = 0; i < numListeners; ++i) {
1439                    tmpListeners.get(i).onTransitionEnd(this);
1440                }
1441            }
1442            for (int i = 0; i < mStartValues.itemIdValues.size(); ++i) {
1443                TransitionValues tv = mStartValues.itemIdValues.valueAt(i);
1444                View v = tv.view;
1445                if (v.hasTransientState()) {
1446                    v.setHasTransientState(false);
1447                }
1448            }
1449            for (int i = 0; i < mEndValues.itemIdValues.size(); ++i) {
1450                TransitionValues tv = mEndValues.itemIdValues.valueAt(i);
1451                View v = tv.view;
1452                if (v.hasTransientState()) {
1453                    v.setHasTransientState(false);
1454                }
1455            }
1456            mEnded = true;
1457        }
1458    }
1459
1460    /**
1461     * This method cancels a transition that is currently running.
1462     *
1463     * @hide
1464     */
1465    protected void cancel() {
1466        int numAnimators = mCurrentAnimators.size();
1467        for (int i = numAnimators - 1; i >= 0; i--) {
1468            Animator animator = mCurrentAnimators.get(i);
1469            animator.cancel();
1470        }
1471        if (mListeners != null && mListeners.size() > 0) {
1472            ArrayList<TransitionListener> tmpListeners =
1473                    (ArrayList<TransitionListener>) mListeners.clone();
1474            int numListeners = tmpListeners.size();
1475            for (int i = 0; i < numListeners; ++i) {
1476                tmpListeners.get(i).onTransitionCancel(this);
1477            }
1478        }
1479    }
1480
1481    /**
1482     * Adds a listener to the set of listeners that are sent events through the
1483     * life of an animation, such as start, repeat, and end.
1484     *
1485     * @param listener the listener to be added to the current set of listeners
1486     * for this animation.
1487     * @return This transition object.
1488     */
1489    public Transition addListener(TransitionListener listener) {
1490        if (mListeners == null) {
1491            mListeners = new ArrayList<TransitionListener>();
1492        }
1493        mListeners.add(listener);
1494        return this;
1495    }
1496
1497    /**
1498     * Removes a listener from the set listening to this animation.
1499     *
1500     * @param listener the listener to be removed from the current set of
1501     * listeners for this transition.
1502     * @return This transition object.
1503     */
1504    public Transition removeListener(TransitionListener listener) {
1505        if (mListeners == null) {
1506            return this;
1507        }
1508        mListeners.remove(listener);
1509        if (mListeners.size() == 0) {
1510            mListeners = null;
1511        }
1512        return this;
1513    }
1514
1515    /**
1516     * Sets the callback to use to find the epicenter of a Transition. A null value indicates
1517     * that there is no epicenter in the Transition and getEpicenter() will return null.
1518     * Transitions like {@link android.transition.Explode} use a point or Rect to orient
1519     * the direction of travel. This is called the epicenter of the Transition and is
1520     * typically centered on a touched View. The
1521     * {@link android.transition.Transition.EpicenterCallback} allows a Transition to
1522     * dynamically retrieve the epicenter during a Transition.
1523     * @param epicenterCallback The callback to use to find the epicenter of the Transition.
1524     */
1525    public void setEpicenterCallback(EpicenterCallback epicenterCallback) {
1526        mEpicenterCallback = epicenterCallback;
1527    }
1528
1529    /**
1530     * Returns the callback used to find the epicenter of the Transition.
1531     * Transitions like {@link android.transition.Explode} use a point or Rect to orient
1532     * the direction of travel. This is called the epicenter of the Transition and is
1533     * typically centered on a touched View. The
1534     * {@link android.transition.Transition.EpicenterCallback} allows a Transition to
1535     * dynamically retrieve the epicenter during a Transition.
1536     * @return the callback used to find the epicenter of the Transition.
1537     */
1538    public EpicenterCallback getEpicenterCallback() {
1539        return mEpicenterCallback;
1540    }
1541
1542    /**
1543     * Returns the epicenter as specified by the
1544     * {@link android.transition.Transition.EpicenterCallback} or null if no callback exists.
1545     * @return the epicenter as specified by the
1546     * {@link android.transition.Transition.EpicenterCallback} or null if no callback exists.
1547     * @see #setEpicenterCallback(android.transition.Transition.EpicenterCallback)
1548     */
1549    public Rect getEpicenter() {
1550        if (mEpicenterCallback == null) {
1551            return null;
1552        }
1553        return mEpicenterCallback.getEpicenter(this);
1554    }
1555
1556    /**
1557     * Sets the method for determining Animator start delays.
1558     * When a Transition affects several Views like {@link android.transition.Explode} or
1559     * {@link android.transition.Slide}, there may be a desire to have a "wave-front" effect
1560     * such that the Animator start delay depends on position of the View. The
1561     * TransitionPropagation specifies how the start delays are calculated.
1562     * @param transitionPropagation The class used to determine the start delay of
1563     *                              Animators created by this Transition. A null value
1564     *                              indicates that no delay should be used.
1565     */
1566    public void setPropagation(TransitionPropagation transitionPropagation) {
1567        mPropagation = transitionPropagation;
1568    }
1569
1570    /**
1571     * Returns the {@link android.transition.TransitionPropagation} used to calculate Animator start
1572     * delays.
1573     * When a Transition affects several Views like {@link android.transition.Explode} or
1574     * {@link android.transition.Slide}, there may be a desire to have a "wave-front" effect
1575     * such that the Animator start delay depends on position of the View. The
1576     * TransitionPropagation specifies how the start delays are calculated.
1577     * @return the {@link android.transition.TransitionPropagation} used to calculate Animator start
1578     * delays. This is null by default.
1579     */
1580    public TransitionPropagation getPropagation() {
1581        return mPropagation;
1582    }
1583
1584    /**
1585     * Captures TransitionPropagation values for the given view and the
1586     * hierarchy underneath it.
1587     */
1588    void capturePropagationValues(TransitionValues transitionValues) {
1589        if (mPropagation != null && !transitionValues.values.isEmpty()) {
1590            String[] propertyNames = mPropagation.getPropagationProperties();
1591            if (propertyNames == null) {
1592                return;
1593            }
1594            boolean containsAll = true;
1595            for (int i = 0; i < propertyNames.length; i++) {
1596                if (!transitionValues.values.containsKey(propertyNames[i])) {
1597                    containsAll = false;
1598                    break;
1599                }
1600            }
1601            if (!containsAll) {
1602                mPropagation.captureValues(transitionValues);
1603            }
1604        }
1605    }
1606
1607    Transition setSceneRoot(ViewGroup sceneRoot) {
1608        mSceneRoot = sceneRoot;
1609        return this;
1610    }
1611
1612    void setCanRemoveViews(boolean canRemoveViews) {
1613        mCanRemoveViews = canRemoveViews;
1614    }
1615
1616    public boolean canRemoveViews() {
1617        return mCanRemoveViews;
1618    }
1619
1620    @Override
1621    public String toString() {
1622        return toString("");
1623    }
1624
1625    @Override
1626    public Transition clone() {
1627        Transition clone = null;
1628        try {
1629            clone = (Transition) super.clone();
1630            clone.mAnimators = new ArrayList<Animator>();
1631            clone.mStartValues = new TransitionValuesMaps();
1632            clone.mEndValues = new TransitionValuesMaps();
1633        } catch (CloneNotSupportedException e) {}
1634
1635        return clone;
1636    }
1637
1638    /**
1639     * Returns the name of this Transition. This name is used internally to distinguish
1640     * between different transitions to determine when interrupting transitions overlap.
1641     * For example, a ChangeBounds running on the same target view as another ChangeBounds
1642     * should determine whether the old transition is animating to different end values
1643     * and should be canceled in favor of the new transition.
1644     *
1645     * <p>By default, a Transition's name is simply the value of {@link Class#getName()},
1646     * but subclasses are free to override and return something different.</p>
1647     *
1648     * @return The name of this transition.
1649     */
1650    public String getName() {
1651        return mName;
1652    }
1653
1654    String toString(String indent) {
1655        String result = indent + getClass().getSimpleName() + "@" +
1656                Integer.toHexString(hashCode()) + ": ";
1657        if (mDuration != -1) {
1658            result += "dur(" + mDuration + ") ";
1659        }
1660        if (mStartDelay != -1) {
1661            result += "dly(" + mStartDelay + ") ";
1662        }
1663        if (mInterpolator != null) {
1664            result += "interp(" + mInterpolator + ") ";
1665        }
1666        if (mTargetIds.size() > 0 || mTargets.size() > 0) {
1667            result += "tgts(";
1668            if (mTargetIds.size() > 0) {
1669                for (int i = 0; i < mTargetIds.size(); ++i) {
1670                    if (i > 0) {
1671                        result += ", ";
1672                    }
1673                    result += mTargetIds.get(i);
1674                }
1675            }
1676            if (mTargets.size() > 0) {
1677                for (int i = 0; i < mTargets.size(); ++i) {
1678                    if (i > 0) {
1679                        result += ", ";
1680                    }
1681                    result += mTargets.get(i);
1682                }
1683            }
1684            result += ")";
1685        }
1686        return result;
1687    }
1688
1689    /**
1690     * A transition listener receives notifications from a transition.
1691     * Notifications indicate transition lifecycle events.
1692     */
1693    public static interface TransitionListener {
1694        /**
1695         * Notification about the start of the transition.
1696         *
1697         * @param transition The started transition.
1698         */
1699        void onTransitionStart(Transition transition);
1700
1701        /**
1702         * Notification about the end of the transition. Canceled transitions
1703         * will always notify listeners of both the cancellation and end
1704         * events. That is, {@link #onTransitionEnd(Transition)} is always called,
1705         * regardless of whether the transition was canceled or played
1706         * through to completion.
1707         *
1708         * @param transition The transition which reached its end.
1709         */
1710        void onTransitionEnd(Transition transition);
1711
1712        /**
1713         * Notification about the cancellation of the transition.
1714         * Note that cancel may be called by a parent {@link TransitionSet} on
1715         * a child transition which has not yet started. This allows the child
1716         * transition to restore state on target objects which was set at
1717         * {@link #createAnimator(android.view.ViewGroup, TransitionValues, TransitionValues)
1718         * createAnimator()} time.
1719         *
1720         * @param transition The transition which was canceled.
1721         */
1722        void onTransitionCancel(Transition transition);
1723
1724        /**
1725         * Notification when a transition is paused.
1726         * Note that createAnimator() may be called by a parent {@link TransitionSet} on
1727         * a child transition which has not yet started. This allows the child
1728         * transition to restore state on target objects which was set at
1729         * {@link #createAnimator(android.view.ViewGroup, TransitionValues, TransitionValues)
1730         * createAnimator()} time.
1731         *
1732         * @param transition The transition which was paused.
1733         */
1734        void onTransitionPause(Transition transition);
1735
1736        /**
1737         * Notification when a transition is resumed.
1738         * Note that resume() may be called by a parent {@link TransitionSet} on
1739         * a child transition which has not yet started. This allows the child
1740         * transition to restore state which may have changed in an earlier call
1741         * to {@link #onTransitionPause(Transition)}.
1742         *
1743         * @param transition The transition which was resumed.
1744         */
1745        void onTransitionResume(Transition transition);
1746    }
1747
1748    /**
1749     * Utility adapter class to avoid having to override all three methods
1750     * whenever someone just wants to listen for a single event.
1751     *
1752     * @hide
1753     * */
1754    public static class TransitionListenerAdapter implements TransitionListener {
1755        @Override
1756        public void onTransitionStart(Transition transition) {
1757        }
1758
1759        @Override
1760        public void onTransitionEnd(Transition transition) {
1761        }
1762
1763        @Override
1764        public void onTransitionCancel(Transition transition) {
1765        }
1766
1767        @Override
1768        public void onTransitionPause(Transition transition) {
1769        }
1770
1771        @Override
1772        public void onTransitionResume(Transition transition) {
1773        }
1774    }
1775
1776    /**
1777     * Holds information about each animator used when a new transition starts
1778     * while other transitions are still running to determine whether a running
1779     * animation should be canceled or a new animation noop'd. The structure holds
1780     * information about the state that an animation is going to, to be compared to
1781     * end state of a new animation.
1782     * @hide
1783     */
1784    public static class AnimationInfo {
1785        public View view;
1786        String name;
1787        TransitionValues values;
1788        WindowId windowId;
1789
1790        AnimationInfo(View view, String name, WindowId windowId, TransitionValues values) {
1791            this.view = view;
1792            this.name = name;
1793            this.values = values;
1794            this.windowId = windowId;
1795        }
1796    }
1797
1798    /**
1799     * Utility class for managing typed ArrayLists efficiently. In particular, this
1800     * can be useful for lists that we don't expect to be used often (eg, the exclude
1801     * lists), so we'd like to keep them nulled out by default. This causes the code to
1802     * become tedious, with constant null checks, code to allocate when necessary,
1803     * and code to null out the reference when the list is empty. This class encapsulates
1804     * all of that functionality into simple add()/remove() methods which perform the
1805     * necessary checks, allocation/null-out as appropriate, and return the
1806     * resulting list.
1807     */
1808    private static class ArrayListManager {
1809
1810        /**
1811         * Add the specified item to the list, returning the resulting list.
1812         * The returned list can either the be same list passed in or, if that
1813         * list was null, the new list that was created.
1814         *
1815         * Note that the list holds unique items; if the item already exists in the
1816         * list, the list is not modified.
1817         */
1818        static <T> ArrayList<T> add(ArrayList<T> list, T item) {
1819            if (list == null) {
1820                list = new ArrayList<T>();
1821            }
1822            if (!list.contains(item)) {
1823                list.add(item);
1824            }
1825            return list;
1826        }
1827
1828        /**
1829         * Remove the specified item from the list, returning the resulting list.
1830         * The returned list can either the be same list passed in or, if that
1831         * list becomes empty as a result of the remove(), the new list was created.
1832         */
1833        static <T> ArrayList<T> remove(ArrayList<T> list, T item) {
1834            if (list != null) {
1835                list.remove(item);
1836                if (list.isEmpty()) {
1837                    list = null;
1838                }
1839            }
1840            return list;
1841        }
1842    }
1843
1844    /**
1845     * Class to get the epicenter of Transition. Use
1846     * {@link #setEpicenterCallback(android.transition.Transition.EpicenterCallback)} to
1847     * set the callback used to calculate the epicenter of the Transition. Override
1848     * {@link #getEpicenter()} to return the rectangular region in screen coordinates of
1849     * the epicenter of the transition.
1850     * @see #setEpicenterCallback(android.transition.Transition.EpicenterCallback)
1851     */
1852    public static abstract class EpicenterCallback {
1853
1854        /**
1855         * Implementers must override to return the epicenter of the Transition in screen
1856         * coordinates. Transitions like {@link android.transition.Explode} depend upon
1857         * an epicenter for the Transition. In Explode, Views move toward or away from the
1858         * center of the epicenter Rect along the vector between the epicenter and the center
1859         * of the View appearing and disappearing. Some Transitions, such as
1860         * {@link android.transition.Fade} pay no attention to the epicenter.
1861         *
1862         * @param transition The transition for which the epicenter applies.
1863         * @return The Rect region of the epicenter of <code>transition</code> or null if
1864         * there is no epicenter.
1865         */
1866        public abstract Rect getEpicenter(Transition transition);
1867    }
1868}
1869