FragmentManager.java revision 5b9fbc316b9c49c57ffbdcdcef1ee83171fd189a
1/*
2 * Copyright (C) 2011 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.support.v4.app;
18
19import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
20
21import android.animation.Animator;
22import android.animation.AnimatorInflater;
23import android.animation.AnimatorListenerAdapter;
24import android.animation.AnimatorSet;
25import android.animation.PropertyValuesHolder;
26import android.animation.ValueAnimator;
27import android.content.Context;
28import android.content.res.Configuration;
29import android.content.res.Resources.NotFoundException;
30import android.content.res.TypedArray;
31import android.os.Build;
32import android.os.Bundle;
33import android.os.Looper;
34import android.os.Parcel;
35import android.os.Parcelable;
36import android.support.annotation.CallSuper;
37import android.support.annotation.IdRes;
38import android.support.annotation.NonNull;
39import android.support.annotation.RestrictTo;
40import android.support.annotation.StringRes;
41import android.support.v4.util.ArraySet;
42import android.support.v4.util.DebugUtils;
43import android.support.v4.util.LogWriter;
44import android.support.v4.util.Pair;
45import android.support.v4.view.ViewCompat;
46import android.util.AttributeSet;
47import android.util.Log;
48import android.util.SparseArray;
49import android.view.LayoutInflater;
50import android.view.Menu;
51import android.view.MenuInflater;
52import android.view.MenuItem;
53import android.view.View;
54import android.view.ViewGroup;
55import android.view.animation.AccelerateInterpolator;
56import android.view.animation.AlphaAnimation;
57import android.view.animation.Animation;
58import android.view.animation.Animation.AnimationListener;
59import android.view.animation.AnimationSet;
60import android.view.animation.AnimationUtils;
61import android.view.animation.DecelerateInterpolator;
62import android.view.animation.Interpolator;
63import android.view.animation.ScaleAnimation;
64
65import java.io.FileDescriptor;
66import java.io.PrintWriter;
67import java.lang.reflect.Field;
68import java.util.ArrayList;
69import java.util.Arrays;
70import java.util.Collections;
71import java.util.List;
72import java.util.concurrent.CopyOnWriteArrayList;
73
74/**
75 * Static library support version of the framework's {@link android.app.FragmentManager}.
76 * Used to write apps that run on platforms prior to Android 3.0.  When running
77 * on Android 3.0 or above, this implementation is still used; it does not try
78 * to switch to the framework's implementation.  See the framework {@link FragmentManager}
79 * documentation for a class overview.
80 *
81 * <p>Your activity must derive from {@link FragmentActivity} to use this. From such an activity,
82 * you can acquire the {@link FragmentManager} by calling
83 * {@link FragmentActivity#getSupportFragmentManager}.
84 */
85public abstract class FragmentManager {
86    /**
87     * Representation of an entry on the fragment back stack, as created
88     * with {@link FragmentTransaction#addToBackStack(String)
89     * FragmentTransaction.addToBackStack()}.  Entries can later be
90     * retrieved with {@link FragmentManager#getBackStackEntryAt(int)
91     * FragmentManager.getBackStackEntryAt()}.
92     *
93     * <p>Note that you should never hold on to a BackStackEntry object;
94     * the identifier as returned by {@link #getId} is the only thing that
95     * will be persisted across activity instances.
96     */
97    public interface BackStackEntry {
98        /**
99         * Return the unique identifier for the entry.  This is the only
100         * representation of the entry that will persist across activity
101         * instances.
102         */
103        public int getId();
104
105        /**
106         * Get the name that was supplied to
107         * {@link FragmentTransaction#addToBackStack(String)
108         * FragmentTransaction.addToBackStack(String)} when creating this entry.
109         */
110        public String getName();
111
112        /**
113         * Return the full bread crumb title resource identifier for the entry,
114         * or 0 if it does not have one.
115         */
116        @StringRes
117        public int getBreadCrumbTitleRes();
118
119        /**
120         * Return the short bread crumb title resource identifier for the entry,
121         * or 0 if it does not have one.
122         */
123        @StringRes
124        public int getBreadCrumbShortTitleRes();
125
126        /**
127         * Return the full bread crumb title for the entry, or null if it
128         * does not have one.
129         */
130        public CharSequence getBreadCrumbTitle();
131
132        /**
133         * Return the short bread crumb title for the entry, or null if it
134         * does not have one.
135         */
136        public CharSequence getBreadCrumbShortTitle();
137    }
138
139    /**
140     * Interface to watch for changes to the back stack.
141     */
142    public interface OnBackStackChangedListener {
143        /**
144         * Called whenever the contents of the back stack change.
145         */
146        public void onBackStackChanged();
147    }
148
149    /**
150     * Start a series of edit operations on the Fragments associated with
151     * this FragmentManager.
152     *
153     * <p>Note: A fragment transaction can only be created/committed prior
154     * to an activity saving its state.  If you try to commit a transaction
155     * after {@link FragmentActivity#onSaveInstanceState FragmentActivity.onSaveInstanceState()}
156     * (and prior to a following {@link FragmentActivity#onStart FragmentActivity.onStart}
157     * or {@link FragmentActivity#onResume FragmentActivity.onResume()}, you will get an error.
158     * This is because the framework takes care of saving your current fragments
159     * in the state, and if changes are made after the state is saved then they
160     * will be lost.</p>
161     */
162    public abstract FragmentTransaction beginTransaction();
163
164    /**
165     * @hide -- remove once prebuilts are in.
166     * @deprecated
167     */
168    @RestrictTo(LIBRARY_GROUP)
169    @Deprecated
170    public FragmentTransaction openTransaction() {
171        return beginTransaction();
172    }
173
174    /**
175     * After a {@link FragmentTransaction} is committed with
176     * {@link FragmentTransaction#commit FragmentTransaction.commit()}, it
177     * is scheduled to be executed asynchronously on the process's main thread.
178     * If you want to immediately executing any such pending operations, you
179     * can call this function (only from the main thread) to do so.  Note that
180     * all callbacks and other related behavior will be done from within this
181     * call, so be careful about where this is called from.
182     *
183     * <p>If you are committing a single transaction that does not modify the
184     * fragment back stack, strongly consider using
185     * {@link FragmentTransaction#commitNow()} instead. This can help avoid
186     * unwanted side effects when other code in your app has pending committed
187     * transactions that expect different timing.</p>
188     * <p>
189     * This also forces the start of any postponed Transactions where
190     * {@link Fragment#postponeEnterTransition()} has been called.
191     *
192     * @return Returns true if there were any pending transactions to be
193     * executed.
194     */
195    public abstract boolean executePendingTransactions();
196
197    /**
198     * Finds a fragment that was identified by the given id either when inflated
199     * from XML or as the container ID when added in a transaction.  This first
200     * searches through fragments that are currently added to the manager's
201     * activity; if no such fragment is found, then all fragments currently
202     * on the back stack associated with this ID are searched.
203     * @return The fragment if found or null otherwise.
204     */
205    public abstract Fragment findFragmentById(@IdRes int id);
206
207    /**
208     * Finds a fragment that was identified by the given tag either when inflated
209     * from XML or as supplied when added in a transaction.  This first
210     * searches through fragments that are currently added to the manager's
211     * activity; if no such fragment is found, then all fragments currently
212     * on the back stack are searched.
213     * @return The fragment if found or null otherwise.
214     */
215    public abstract Fragment findFragmentByTag(String tag);
216
217    /**
218     * Flag for {@link #popBackStack(String, int)}
219     * and {@link #popBackStack(int, int)}: If set, and the name or ID of
220     * a back stack entry has been supplied, then all matching entries will
221     * be consumed until one that doesn't match is found or the bottom of
222     * the stack is reached.  Otherwise, all entries up to but not including that entry
223     * will be removed.
224     */
225    public static final int POP_BACK_STACK_INCLUSIVE = 1<<0;
226
227    /**
228     * Pop the top state off the back stack.  Returns true if there was one
229     * to pop, else false.  This function is asynchronous -- it enqueues the
230     * request to pop, but the action will not be performed until the application
231     * returns to its event loop.
232     */
233    public abstract void popBackStack();
234
235    /**
236     * Like {@link #popBackStack()}, but performs the operation immediately
237     * inside of the call.  This is like calling {@link #executePendingTransactions()}
238     * afterwards without forcing the start of postponed Transactions.
239     * @return Returns true if there was something popped, else false.
240     */
241    public abstract boolean popBackStackImmediate();
242
243    /**
244     * Pop the last fragment transition from the manager's fragment
245     * back stack.  If there is nothing to pop, false is returned.
246     * This function is asynchronous -- it enqueues the
247     * request to pop, but the action will not be performed until the application
248     * returns to its event loop.
249     *
250     * @param name If non-null, this is the name of a previous back state
251     * to look for; if found, all states up to that state will be popped.  The
252     * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether
253     * the named state itself is popped. If null, only the top state is popped.
254     * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}.
255     */
256    public abstract void popBackStack(String name, int flags);
257
258    /**
259     * Like {@link #popBackStack(String, int)}, but performs the operation immediately
260     * inside of the call.  This is like calling {@link #executePendingTransactions()}
261     * afterwards without forcing the start of postponed Transactions.
262     * @return Returns true if there was something popped, else false.
263     */
264    public abstract boolean popBackStackImmediate(String name, int flags);
265
266    /**
267     * Pop all back stack states up to the one with the given identifier.
268     * This function is asynchronous -- it enqueues the
269     * request to pop, but the action will not be performed until the application
270     * returns to its event loop.
271     *
272     * @param id Identifier of the stated to be popped. If no identifier exists,
273     * false is returned.
274     * The identifier is the number returned by
275     * {@link FragmentTransaction#commit() FragmentTransaction.commit()}.  The
276     * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether
277     * the named state itself is popped.
278     * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}.
279     */
280    public abstract void popBackStack(int id, int flags);
281
282    /**
283     * Like {@link #popBackStack(int, int)}, but performs the operation immediately
284     * inside of the call.  This is like calling {@link #executePendingTransactions()}
285     * afterwards without forcing the start of postponed Transactions.
286     * @return Returns true if there was something popped, else false.
287     */
288    public abstract boolean popBackStackImmediate(int id, int flags);
289
290    /**
291     * Return the number of entries currently in the back stack.
292     */
293    public abstract int getBackStackEntryCount();
294
295    /**
296     * Return the BackStackEntry at index <var>index</var> in the back stack;
297     * entries start index 0 being the bottom of the stack.
298     */
299    public abstract BackStackEntry getBackStackEntryAt(int index);
300
301    /**
302     * Add a new listener for changes to the fragment back stack.
303     */
304    public abstract void addOnBackStackChangedListener(OnBackStackChangedListener listener);
305
306    /**
307     * Remove a listener that was previously added with
308     * {@link #addOnBackStackChangedListener(OnBackStackChangedListener)}.
309     */
310    public abstract void removeOnBackStackChangedListener(OnBackStackChangedListener listener);
311
312    /**
313     * Put a reference to a fragment in a Bundle.  This Bundle can be
314     * persisted as saved state, and when later restoring
315     * {@link #getFragment(Bundle, String)} will return the current
316     * instance of the same fragment.
317     *
318     * @param bundle The bundle in which to put the fragment reference.
319     * @param key The name of the entry in the bundle.
320     * @param fragment The Fragment whose reference is to be stored.
321     */
322    public abstract void putFragment(Bundle bundle, String key, Fragment fragment);
323
324    /**
325     * Retrieve the current Fragment instance for a reference previously
326     * placed with {@link #putFragment(Bundle, String, Fragment)}.
327     *
328     * @param bundle The bundle from which to retrieve the fragment reference.
329     * @param key The name of the entry in the bundle.
330     * @return Returns the current Fragment instance that is associated with
331     * the given reference.
332     */
333    public abstract Fragment getFragment(Bundle bundle, String key);
334
335    /**
336     * Get a list of all fragments that are currently added to the FragmentManager.
337     * This may include those that are hidden as well as those that are shown.
338     * This will not include any fragments only in the back stack, or fragments that
339     * are detached or removed.
340     * <p>
341     * The order of the fragments in the list is the order in which they were
342     * added or attached.
343     *
344     * @return A list of all fragments that are added to the FragmentManager.
345     */
346    public abstract List<Fragment> getFragments();
347
348    /**
349     * Save the current instance state of the given Fragment.  This can be
350     * used later when creating a new instance of the Fragment and adding
351     * it to the fragment manager, to have it create itself to match the
352     * current state returned here.  Note that there are limits on how
353     * this can be used:
354     *
355     * <ul>
356     * <li>The Fragment must currently be attached to the FragmentManager.
357     * <li>A new Fragment created using this saved state must be the same class
358     * type as the Fragment it was created from.
359     * <li>The saved state can not contain dependencies on other fragments --
360     * that is it can't use {@link #putFragment(Bundle, String, Fragment)} to
361     * store a fragment reference because that reference may not be valid when
362     * this saved state is later used.  Likewise the Fragment's target and
363     * result code are not included in this state.
364     * </ul>
365     *
366     * @param f The Fragment whose state is to be saved.
367     * @return The generated state.  This will be null if there was no
368     * interesting state created by the fragment.
369     */
370    public abstract Fragment.SavedState saveFragmentInstanceState(Fragment f);
371
372    /**
373     * Returns true if the final {@link android.app.Activity#onDestroy() Activity.onDestroy()}
374     * call has been made on the FragmentManager's Activity, so this instance is now dead.
375     */
376    public abstract boolean isDestroyed();
377
378    /**
379     * Registers a {@link FragmentLifecycleCallbacks} to listen to fragment lifecycle events
380     * happening in this FragmentManager. All registered callbacks will be automatically
381     * unregistered when this FragmentManager is destroyed.
382     *
383     * @param cb Callbacks to register
384     * @param recursive true to automatically register this callback for all child FragmentManagers
385     */
386    public abstract void registerFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb,
387            boolean recursive);
388
389    /**
390     * Unregisters a previously registered {@link FragmentLifecycleCallbacks}. If the callback
391     * was not previously registered this call has no effect. All registered callbacks will be
392     * automatically unregistered when this FragmentManager is destroyed.
393     *
394     * @param cb Callbacks to unregister
395     */
396    public abstract void unregisterFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb);
397
398    /**
399     * Return the currently active primary navigation fragment for this FragmentManager.
400     * The primary navigation fragment is set by fragment transactions using
401     * {@link FragmentTransaction#setPrimaryNavigationFragment(Fragment)}.
402     *
403     * <p>The primary navigation fragment's
404     * {@link Fragment#getChildFragmentManager() child FragmentManager} will be called first
405     * to process delegated navigation actions such as {@link #popBackStack()} if no ID
406     * or transaction name is provided to pop to.</p>
407     *
408     * @return the fragment designated as the primary navigation fragment
409     */
410    public abstract Fragment getPrimaryNavigationFragment();
411
412    /**
413     * Print the FragmentManager's state into the given stream.
414     *
415     * @param prefix Text to print at the front of each line.
416     * @param fd The raw file descriptor that the dump is being sent to.
417     * @param writer A PrintWriter to which the dump is to be set.
418     * @param args Additional arguments to the dump request.
419     */
420    public abstract void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args);
421
422    /**
423     * Control whether the framework's internal fragment manager debugging
424     * logs are turned on.  If enabled, you will see output in logcat as
425     * the framework performs fragment operations.
426     */
427    public static void enableDebugLogging(boolean enabled) {
428        FragmentManagerImpl.DEBUG = enabled;
429    }
430
431    /**
432     * Returns {@code true} if the FragmentManager's state has already been saved
433     * by its host. Any operations that would change saved state should not be performed
434     * if this method returns true. For example, any popBackStack() method, such as
435     * {@link #popBackStackImmediate()} or any FragmentTransaction using
436     * {@link FragmentTransaction#commit()} instead of
437     * {@link FragmentTransaction#commitAllowingStateLoss()} will change
438     * the state and will result in an error.
439     *
440     * @return true if this FragmentManager's state has already been saved by its host
441     */
442    public abstract boolean isStateSaved();
443
444    /**
445     * Callback interface for listening to fragment state changes that happen
446     * within a given FragmentManager.
447     */
448    public abstract static class FragmentLifecycleCallbacks {
449        /**
450         * Called right before the fragment's {@link Fragment#onAttach(Context)} method is called.
451         * This is a good time to inject any required dependencies or perform other configuration
452         * for the fragment before any of the fragment's lifecycle methods are invoked.
453         *
454         * @param fm Host FragmentManager
455         * @param f Fragment changing state
456         * @param context Context that the Fragment is being attached to
457         */
458        public void onFragmentPreAttached(FragmentManager fm, Fragment f, Context context) {}
459
460        /**
461         * Called after the fragment has been attached to its host. Its host will have had
462         * <code>onAttachFragment</code> called before this call happens.
463         *
464         * @param fm Host FragmentManager
465         * @param f Fragment changing state
466         * @param context Context that the Fragment was attached to
467         */
468        public void onFragmentAttached(FragmentManager fm, Fragment f, Context context) {}
469
470        /**
471         * Called right before the fragment's {@link Fragment#onCreate(Bundle)} method is called.
472         * This is a good time to inject any required dependencies or perform other configuration
473         * for the fragment.
474         *
475         * @param fm Host FragmentManager
476         * @param f Fragment changing state
477         * @param savedInstanceState Saved instance bundle from a previous instance
478         */
479        public void onFragmentPreCreated(FragmentManager fm, Fragment f,
480                Bundle savedInstanceState) {}
481
482        /**
483         * Called after the fragment has returned from the FragmentManager's call to
484         * {@link Fragment#onCreate(Bundle)}. This will only happen once for any given
485         * fragment instance, though the fragment may be attached and detached multiple times.
486         *
487         * @param fm Host FragmentManager
488         * @param f Fragment changing state
489         * @param savedInstanceState Saved instance bundle from a previous instance
490         */
491        public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) {}
492
493        /**
494         * Called after the fragment has returned from the FragmentManager's call to
495         * {@link Fragment#onActivityCreated(Bundle)}. This will only happen once for any given
496         * fragment instance, though the fragment may be attached and detached multiple times.
497         *
498         * @param fm Host FragmentManager
499         * @param f Fragment changing state
500         * @param savedInstanceState Saved instance bundle from a previous instance
501         */
502        public void onFragmentActivityCreated(FragmentManager fm, Fragment f,
503                Bundle savedInstanceState) {}
504
505        /**
506         * Called after the fragment has returned a non-null view from the FragmentManager's
507         * request to {@link Fragment#onCreateView(LayoutInflater, ViewGroup, Bundle)}.
508         *
509         * @param fm Host FragmentManager
510         * @param f Fragment that created and owns the view
511         * @param v View returned by the fragment
512         * @param savedInstanceState Saved instance bundle from a previous instance
513         */
514        public void onFragmentViewCreated(FragmentManager fm, Fragment f, View v,
515                Bundle savedInstanceState) {}
516
517        /**
518         * Called after the fragment has returned from the FragmentManager's call to
519         * {@link Fragment#onStart()}.
520         *
521         * @param fm Host FragmentManager
522         * @param f Fragment changing state
523         */
524        public void onFragmentStarted(FragmentManager fm, Fragment f) {}
525
526        /**
527         * Called after the fragment has returned from the FragmentManager's call to
528         * {@link Fragment#onResume()}.
529         *
530         * @param fm Host FragmentManager
531         * @param f Fragment changing state
532         */
533        public void onFragmentResumed(FragmentManager fm, Fragment f) {}
534
535        /**
536         * Called after the fragment has returned from the FragmentManager's call to
537         * {@link Fragment#onPause()}.
538         *
539         * @param fm Host FragmentManager
540         * @param f Fragment changing state
541         */
542        public void onFragmentPaused(FragmentManager fm, Fragment f) {}
543
544        /**
545         * Called after the fragment has returned from the FragmentManager's call to
546         * {@link Fragment#onStop()}.
547         *
548         * @param fm Host FragmentManager
549         * @param f Fragment changing state
550         */
551        public void onFragmentStopped(FragmentManager fm, Fragment f) {}
552
553        /**
554         * Called after the fragment has returned from the FragmentManager's call to
555         * {@link Fragment#onSaveInstanceState(Bundle)}.
556         *
557         * @param fm Host FragmentManager
558         * @param f Fragment changing state
559         * @param outState Saved state bundle for the fragment
560         */
561        public void onFragmentSaveInstanceState(FragmentManager fm, Fragment f, Bundle outState) {}
562
563        /**
564         * Called after the fragment has returned from the FragmentManager's call to
565         * {@link Fragment#onDestroyView()}.
566         *
567         * @param fm Host FragmentManager
568         * @param f Fragment changing state
569         */
570        public void onFragmentViewDestroyed(FragmentManager fm, Fragment f) {}
571
572        /**
573         * Called after the fragment has returned from the FragmentManager's call to
574         * {@link Fragment#onDestroy()}.
575         *
576         * @param fm Host FragmentManager
577         * @param f Fragment changing state
578         */
579        public void onFragmentDestroyed(FragmentManager fm, Fragment f) {}
580
581        /**
582         * Called after the fragment has returned from the FragmentManager's call to
583         * {@link Fragment#onDetach()}.
584         *
585         * @param fm Host FragmentManager
586         * @param f Fragment changing state
587         */
588        public void onFragmentDetached(FragmentManager fm, Fragment f) {}
589    }
590}
591
592final class FragmentManagerState implements Parcelable {
593    FragmentState[] mActive;
594    int[] mAdded;
595    BackStackState[] mBackStack;
596    int mPrimaryNavActiveIndex = -1;
597    int mNextFragmentIndex;
598
599    public FragmentManagerState() {
600    }
601
602    public FragmentManagerState(Parcel in) {
603        mActive = in.createTypedArray(FragmentState.CREATOR);
604        mAdded = in.createIntArray();
605        mBackStack = in.createTypedArray(BackStackState.CREATOR);
606        mPrimaryNavActiveIndex = in.readInt();
607        mNextFragmentIndex = in.readInt();
608    }
609
610    @Override
611    public int describeContents() {
612        return 0;
613    }
614
615    @Override
616    public void writeToParcel(Parcel dest, int flags) {
617        dest.writeTypedArray(mActive, flags);
618        dest.writeIntArray(mAdded);
619        dest.writeTypedArray(mBackStack, flags);
620        dest.writeInt(mPrimaryNavActiveIndex);
621        dest.writeInt(mNextFragmentIndex);
622    }
623
624    public static final Parcelable.Creator<FragmentManagerState> CREATOR
625            = new Parcelable.Creator<FragmentManagerState>() {
626        @Override
627        public FragmentManagerState createFromParcel(Parcel in) {
628            return new FragmentManagerState(in);
629        }
630
631        @Override
632        public FragmentManagerState[] newArray(int size) {
633            return new FragmentManagerState[size];
634        }
635    };
636}
637
638/**
639 * Container for fragments associated with an activity.
640 */
641final class FragmentManagerImpl extends FragmentManager implements LayoutInflater.Factory2 {
642    static boolean DEBUG = false;
643    static final String TAG = "FragmentManager";
644
645    static final String TARGET_REQUEST_CODE_STATE_TAG = "android:target_req_state";
646    static final String TARGET_STATE_TAG = "android:target_state";
647    static final String VIEW_STATE_TAG = "android:view_state";
648    static final String USER_VISIBLE_HINT_TAG = "android:user_visible_hint";
649
650    ArrayList<OpGenerator> mPendingActions;
651    boolean mExecutingActions;
652
653    int mNextFragmentIndex = 0;
654
655    final ArrayList<Fragment> mAdded = new ArrayList<>();
656    SparseArray<Fragment> mActive;
657    ArrayList<BackStackRecord> mBackStack;
658    ArrayList<Fragment> mCreatedMenus;
659
660    // Must be accessed while locked.
661    ArrayList<BackStackRecord> mBackStackIndices;
662    ArrayList<Integer> mAvailBackStackIndices;
663
664    ArrayList<OnBackStackChangedListener> mBackStackChangeListeners;
665    private final CopyOnWriteArrayList<Pair<FragmentLifecycleCallbacks, Boolean>>
666            mLifecycleCallbacks = new CopyOnWriteArrayList<>();
667
668    int mCurState = Fragment.INITIALIZING;
669    FragmentHostCallback mHost;
670    FragmentContainer mContainer;
671    Fragment mParent;
672    Fragment mPrimaryNav;
673
674    static Field sAnimationListenerField = null;
675
676    boolean mNeedMenuInvalidate;
677    boolean mStateSaved;
678    boolean mDestroyed;
679    String mNoTransactionsBecause;
680    boolean mHavePendingDeferredStart;
681
682    // Temporary vars for removing redundant operations in BackStackRecords:
683    ArrayList<BackStackRecord> mTmpRecords;
684    ArrayList<Boolean> mTmpIsPop;
685    ArrayList<Fragment> mTmpAddedFragments;
686
687    // Temporary vars for state save and restore.
688    Bundle mStateBundle = null;
689    SparseArray<Parcelable> mStateArray = null;
690
691    // Postponed transactions.
692    ArrayList<StartEnterTransitionListener> mPostponedTransactions;
693
694    // Saved FragmentManagerNonConfig during saveAllState() and cleared in noteStateNotSaved()
695    FragmentManagerNonConfig mSavedNonConfig;
696
697    Runnable mExecCommit = new Runnable() {
698        @Override
699        public void run() {
700            execPendingActions();
701        }
702    };
703
704    static boolean modifiesAlpha(AnimationOrAnimator anim) {
705        if (anim.animation instanceof AlphaAnimation) {
706            return true;
707        } else if (anim.animation instanceof AnimationSet) {
708            List<Animation> anims = ((AnimationSet) anim.animation).getAnimations();
709            for (int i = 0; i < anims.size(); i++) {
710                if (anims.get(i) instanceof AlphaAnimation) {
711                    return true;
712                }
713            }
714            return false;
715        } else {
716            return modifiesAlpha(anim.animator);
717        }
718    }
719
720    static boolean modifiesAlpha(Animator anim) {
721        if (anim == null) {
722            return false;
723        }
724        if (anim instanceof ValueAnimator) {
725            ValueAnimator valueAnim = (ValueAnimator) anim;
726            PropertyValuesHolder[] values = valueAnim.getValues();
727            for (int i = 0; i < values.length; i++) {
728                if (("alpha").equals(values[i].getPropertyName())) {
729                    return true;
730                }
731            }
732        } else if (anim instanceof AnimatorSet) {
733            List<Animator> animList = ((AnimatorSet) anim).getChildAnimations();
734            for (int i = 0; i < animList.size(); i++) {
735                if (modifiesAlpha(animList.get(i))) {
736                    return true;
737                }
738            }
739        }
740        return false;
741    }
742
743    static boolean shouldRunOnHWLayer(View v, AnimationOrAnimator anim) {
744        if (v == null || anim == null) {
745            return false;
746        }
747        return Build.VERSION.SDK_INT >= 19
748                && v.getLayerType() == View.LAYER_TYPE_NONE
749                && ViewCompat.hasOverlappingRendering(v)
750                && modifiesAlpha(anim);
751    }
752
753    private void throwException(RuntimeException ex) {
754        Log.e(TAG, ex.getMessage());
755        Log.e(TAG, "Activity state:");
756        LogWriter logw = new LogWriter(TAG);
757        PrintWriter pw = new PrintWriter(logw);
758        if (mHost != null) {
759            try {
760                mHost.onDump("  ", null, pw, new String[] { });
761            } catch (Exception e) {
762                Log.e(TAG, "Failed dumping state", e);
763            }
764        } else {
765            try {
766                dump("  ", null, pw, new String[] { });
767            } catch (Exception e) {
768                Log.e(TAG, "Failed dumping state", e);
769            }
770        }
771        throw ex;
772    }
773
774    @Override
775    public FragmentTransaction beginTransaction() {
776        return new BackStackRecord(this);
777    }
778
779    @Override
780    public boolean executePendingTransactions() {
781        boolean updates = execPendingActions();
782        forcePostponedTransactions();
783        return updates;
784    }
785
786    @Override
787    public void popBackStack() {
788        enqueueAction(new PopBackStackState(null, -1, 0), false);
789    }
790
791    @Override
792    public boolean popBackStackImmediate() {
793        checkStateLoss();
794        return popBackStackImmediate(null, -1, 0);
795    }
796
797    @Override
798    public void popBackStack(final String name, final int flags) {
799        enqueueAction(new PopBackStackState(name, -1, flags), false);
800    }
801
802    @Override
803    public boolean popBackStackImmediate(String name, int flags) {
804        checkStateLoss();
805        return popBackStackImmediate(name, -1, flags);
806    }
807
808    @Override
809    public void popBackStack(final int id, final int flags) {
810        if (id < 0) {
811            throw new IllegalArgumentException("Bad id: " + id);
812        }
813        enqueueAction(new PopBackStackState(null, id, flags), false);
814    }
815
816    @Override
817    public boolean popBackStackImmediate(int id, int flags) {
818        checkStateLoss();
819        execPendingActions();
820        if (id < 0) {
821            throw new IllegalArgumentException("Bad id: " + id);
822        }
823        return popBackStackImmediate(null, id, flags);
824    }
825
826    /**
827     * Used by all public popBackStackImmediate methods, this executes pending transactions and
828     * returns true if the pop action did anything, regardless of what other pending
829     * transactions did.
830     *
831     * @return true if the pop operation did anything or false otherwise.
832     */
833    private boolean popBackStackImmediate(String name, int id, int flags) {
834        execPendingActions();
835        ensureExecReady(true);
836
837        if (mPrimaryNav != null // We have a primary nav fragment
838                && id < 0 // No valid id (since they're local)
839                && name == null) { // no name to pop to (since they're local)
840            final FragmentManager childManager = mPrimaryNav.peekChildFragmentManager();
841            if (childManager != null && childManager.popBackStackImmediate()) {
842                // We did something, just not to this specific FragmentManager. Return true.
843                return true;
844            }
845        }
846
847        boolean executePop = popBackStackState(mTmpRecords, mTmpIsPop, name, id, flags);
848        if (executePop) {
849            mExecutingActions = true;
850            try {
851                removeRedundantOperationsAndExecute(mTmpRecords, mTmpIsPop);
852            } finally {
853                cleanupExec();
854            }
855        }
856
857        doPendingDeferredStart();
858        burpActive();
859        return executePop;
860    }
861
862    @Override
863    public int getBackStackEntryCount() {
864        return mBackStack != null ? mBackStack.size() : 0;
865    }
866
867    @Override
868    public BackStackEntry getBackStackEntryAt(int index) {
869        return mBackStack.get(index);
870    }
871
872    @Override
873    public void addOnBackStackChangedListener(OnBackStackChangedListener listener) {
874        if (mBackStackChangeListeners == null) {
875            mBackStackChangeListeners = new ArrayList<OnBackStackChangedListener>();
876        }
877        mBackStackChangeListeners.add(listener);
878    }
879
880    @Override
881    public void removeOnBackStackChangedListener(OnBackStackChangedListener listener) {
882        if (mBackStackChangeListeners != null) {
883            mBackStackChangeListeners.remove(listener);
884        }
885    }
886
887    @Override
888    public void putFragment(Bundle bundle, String key, Fragment fragment) {
889        if (fragment.mIndex < 0) {
890            throwException(new IllegalStateException("Fragment " + fragment
891                    + " is not currently in the FragmentManager"));
892        }
893        bundle.putInt(key, fragment.mIndex);
894    }
895
896    @Override
897    public Fragment getFragment(Bundle bundle, String key) {
898        int index = bundle.getInt(key, -1);
899        if (index == -1) {
900            return null;
901        }
902        Fragment f = mActive.get(index);
903        if (f == null) {
904            throwException(new IllegalStateException("Fragment no longer exists for key "
905                    + key + ": index " + index));
906        }
907        return f;
908    }
909
910    @Override
911    public List<Fragment> getFragments() {
912        if (mAdded.isEmpty()) {
913            return Collections.EMPTY_LIST;
914        }
915        synchronized (mAdded) {
916            return (List<Fragment>) mAdded.clone();
917        }
918    }
919
920    /**
921     * This is used by FragmentController to get the Active fragments.
922     *
923     * @return A list of active fragments in the fragment manager, including those that are in the
924     * back stack.
925     */
926    List<Fragment> getActiveFragments() {
927        if (mActive == null) {
928            return null;
929        }
930        final int count = mActive.size();
931        ArrayList<Fragment> fragments = new ArrayList<>(count);
932        for (int i = 0; i < count; i++) {
933            fragments.add(mActive.valueAt(i));
934        }
935        return fragments;
936    }
937
938    /**
939     * Used by FragmentController to get the number of Active Fragments.
940     *
941     * @return The number of active fragments.
942     */
943    int getActiveFragmentCount() {
944        if (mActive == null) {
945            return 0;
946        }
947        return mActive.size();
948    }
949
950    @Override
951    public Fragment.SavedState saveFragmentInstanceState(Fragment fragment) {
952        if (fragment.mIndex < 0) {
953            throwException( new IllegalStateException("Fragment " + fragment
954                    + " is not currently in the FragmentManager"));
955        }
956        if (fragment.mState > Fragment.INITIALIZING) {
957            Bundle result = saveFragmentBasicState(fragment);
958            return result != null ? new Fragment.SavedState(result) : null;
959        }
960        return null;
961    }
962
963    @Override
964    public boolean isDestroyed() {
965        return mDestroyed;
966    }
967
968    @Override
969    public String toString() {
970        StringBuilder sb = new StringBuilder(128);
971        sb.append("FragmentManager{");
972        sb.append(Integer.toHexString(System.identityHashCode(this)));
973        sb.append(" in ");
974        if (mParent != null) {
975            DebugUtils.buildShortClassTag(mParent, sb);
976        } else {
977            DebugUtils.buildShortClassTag(mHost, sb);
978        }
979        sb.append("}}");
980        return sb.toString();
981    }
982
983    @Override
984    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
985        String innerPrefix = prefix + "    ";
986
987        int N;
988        if (mActive != null) {
989            N = mActive.size();
990            if (N > 0) {
991                writer.print(prefix); writer.print("Active Fragments in ");
992                        writer.print(Integer.toHexString(System.identityHashCode(this)));
993                        writer.println(":");
994                for (int i=0; i<N; i++) {
995                    Fragment f = mActive.valueAt(i);
996                    writer.print(prefix); writer.print("  #"); writer.print(i);
997                            writer.print(": "); writer.println(f);
998                    if (f != null) {
999                        f.dump(innerPrefix, fd, writer, args);
1000                    }
1001                }
1002            }
1003        }
1004
1005        N = mAdded.size();
1006        if (N > 0) {
1007            writer.print(prefix); writer.println("Added Fragments:");
1008            for (int i = 0; i < N; i++) {
1009                Fragment f = mAdded.get(i);
1010                writer.print(prefix);
1011                writer.print("  #");
1012                writer.print(i);
1013                writer.print(": ");
1014                writer.println(f.toString());
1015            }
1016        }
1017
1018        if (mCreatedMenus != null) {
1019            N = mCreatedMenus.size();
1020            if (N > 0) {
1021                writer.print(prefix); writer.println("Fragments Created Menus:");
1022                for (int i=0; i<N; i++) {
1023                    Fragment f = mCreatedMenus.get(i);
1024                    writer.print(prefix); writer.print("  #"); writer.print(i);
1025                            writer.print(": "); writer.println(f.toString());
1026                }
1027            }
1028        }
1029
1030        if (mBackStack != null) {
1031            N = mBackStack.size();
1032            if (N > 0) {
1033                writer.print(prefix); writer.println("Back Stack:");
1034                for (int i=0; i<N; i++) {
1035                    BackStackRecord bs = mBackStack.get(i);
1036                    writer.print(prefix); writer.print("  #"); writer.print(i);
1037                            writer.print(": "); writer.println(bs.toString());
1038                    bs.dump(innerPrefix, fd, writer, args);
1039                }
1040            }
1041        }
1042
1043        synchronized (this) {
1044            if (mBackStackIndices != null) {
1045                N = mBackStackIndices.size();
1046                if (N > 0) {
1047                    writer.print(prefix); writer.println("Back Stack Indices:");
1048                    for (int i=0; i<N; i++) {
1049                        BackStackRecord bs = mBackStackIndices.get(i);
1050                        writer.print(prefix); writer.print("  #"); writer.print(i);
1051                                writer.print(": "); writer.println(bs);
1052                    }
1053                }
1054            }
1055
1056            if (mAvailBackStackIndices != null && mAvailBackStackIndices.size() > 0) {
1057                writer.print(prefix); writer.print("mAvailBackStackIndices: ");
1058                        writer.println(Arrays.toString(mAvailBackStackIndices.toArray()));
1059            }
1060        }
1061
1062        if (mPendingActions != null) {
1063            N = mPendingActions.size();
1064            if (N > 0) {
1065                writer.print(prefix); writer.println("Pending Actions:");
1066                for (int i=0; i<N; i++) {
1067                    OpGenerator r = mPendingActions.get(i);
1068                    writer.print(prefix); writer.print("  #"); writer.print(i);
1069                            writer.print(": "); writer.println(r);
1070                }
1071            }
1072        }
1073
1074        writer.print(prefix); writer.println("FragmentManager misc state:");
1075        writer.print(prefix); writer.print("  mHost="); writer.println(mHost);
1076        writer.print(prefix); writer.print("  mContainer="); writer.println(mContainer);
1077        if (mParent != null) {
1078            writer.print(prefix); writer.print("  mParent="); writer.println(mParent);
1079        }
1080        writer.print(prefix); writer.print("  mCurState="); writer.print(mCurState);
1081                writer.print(" mStateSaved="); writer.print(mStateSaved);
1082                writer.print(" mDestroyed="); writer.println(mDestroyed);
1083        if (mNeedMenuInvalidate) {
1084            writer.print(prefix); writer.print("  mNeedMenuInvalidate=");
1085                    writer.println(mNeedMenuInvalidate);
1086        }
1087        if (mNoTransactionsBecause != null) {
1088            writer.print(prefix); writer.print("  mNoTransactionsBecause=");
1089                    writer.println(mNoTransactionsBecause);
1090        }
1091    }
1092
1093    static final Interpolator DECELERATE_QUINT = new DecelerateInterpolator(2.5f);
1094    static final Interpolator DECELERATE_CUBIC = new DecelerateInterpolator(1.5f);
1095    static final Interpolator ACCELERATE_QUINT = new AccelerateInterpolator(2.5f);
1096    static final Interpolator ACCELERATE_CUBIC = new AccelerateInterpolator(1.5f);
1097
1098    static final int ANIM_DUR = 220;
1099
1100    static AnimationOrAnimator makeOpenCloseAnimation(Context context, float startScale,
1101            float endScale, float startAlpha, float endAlpha) {
1102        AnimationSet set = new AnimationSet(false);
1103        ScaleAnimation scale = new ScaleAnimation(startScale, endScale, startScale, endScale,
1104                Animation.RELATIVE_TO_SELF, .5f, Animation.RELATIVE_TO_SELF, .5f);
1105        scale.setInterpolator(DECELERATE_QUINT);
1106        scale.setDuration(ANIM_DUR);
1107        set.addAnimation(scale);
1108        AlphaAnimation alpha = new AlphaAnimation(startAlpha, endAlpha);
1109        alpha.setInterpolator(DECELERATE_CUBIC);
1110        alpha.setDuration(ANIM_DUR);
1111        set.addAnimation(alpha);
1112        return new AnimationOrAnimator(set);
1113    }
1114
1115    static AnimationOrAnimator makeFadeAnimation(Context context, float start, float end) {
1116        AlphaAnimation anim = new AlphaAnimation(start, end);
1117        anim.setInterpolator(DECELERATE_CUBIC);
1118        anim.setDuration(ANIM_DUR);
1119        return new AnimationOrAnimator(anim);
1120    }
1121
1122    AnimationOrAnimator loadAnimation(Fragment fragment, int transit, boolean enter,
1123            int transitionStyle) {
1124        int nextAnim = fragment.getNextAnim();
1125        Animation animation = fragment.onCreateAnimation(transit, enter, nextAnim);
1126        if (animation != null) {
1127            return new AnimationOrAnimator(animation);
1128        }
1129
1130        Animator animator = fragment.onCreateAnimator(transit, enter, nextAnim);
1131        if (animator != null) {
1132            return new AnimationOrAnimator(animator);
1133        }
1134
1135        if (nextAnim != 0) {
1136            String dir = mHost.getContext().getResources().getResourceTypeName(nextAnim);
1137            boolean isAnim = "anim".equals(dir);
1138            boolean successfulLoad = false;
1139            if (isAnim) {
1140                // try AnimationUtils first
1141                try {
1142                    animation = AnimationUtils.loadAnimation(mHost.getContext(), nextAnim);
1143                    if (animation != null) {
1144                        return new AnimationOrAnimator(animation);
1145                    }
1146                    // A null animation may be returned and that is acceptable
1147                    successfulLoad = true; // succeeded in loading animation, but it is null
1148                } catch (NotFoundException e) {
1149                    throw e; // Rethrow it -- the resource should be found if it is provided.
1150                } catch (RuntimeException e) {
1151                    // Other exceptions can occur when loading an Animator from AnimationUtils.
1152                }
1153            }
1154            if (!successfulLoad) {
1155                // try Animator
1156                try {
1157                    animator = AnimatorInflater.loadAnimator(mHost.getContext(), nextAnim);
1158                    if (animator != null) {
1159                        return new AnimationOrAnimator(animator);
1160                    }
1161                } catch (RuntimeException e) {
1162                    if (isAnim) {
1163                        // Rethrow it -- we already tried AnimationUtils and it failed.
1164                        throw e;
1165                    }
1166                    // Otherwise, it is probably an animation resource
1167                    animation = AnimationUtils.loadAnimation(mHost.getContext(), nextAnim);
1168                    if (animation != null) {
1169                        return new AnimationOrAnimator(animation);
1170                    }
1171                }
1172            }
1173        }
1174
1175        if (transit == 0) {
1176            return null;
1177        }
1178
1179        int styleIndex = transitToStyleIndex(transit, enter);
1180        if (styleIndex < 0) {
1181            return null;
1182        }
1183
1184        switch (styleIndex) {
1185            case ANIM_STYLE_OPEN_ENTER:
1186                return makeOpenCloseAnimation(mHost.getContext(), 1.125f, 1.0f, 0, 1);
1187            case ANIM_STYLE_OPEN_EXIT:
1188                return makeOpenCloseAnimation(mHost.getContext(), 1.0f, .975f, 1, 0);
1189            case ANIM_STYLE_CLOSE_ENTER:
1190                return makeOpenCloseAnimation(mHost.getContext(), .975f, 1.0f, 0, 1);
1191            case ANIM_STYLE_CLOSE_EXIT:
1192                return makeOpenCloseAnimation(mHost.getContext(), 1.0f, 1.075f, 1, 0);
1193            case ANIM_STYLE_FADE_ENTER:
1194                return makeFadeAnimation(mHost.getContext(), 0, 1);
1195            case ANIM_STYLE_FADE_EXIT:
1196                return makeFadeAnimation(mHost.getContext(), 1, 0);
1197        }
1198
1199        // TODO: remove or fix transitionStyle -- it apparently never worked.
1200        if (transitionStyle == 0 && mHost.onHasWindowAnimations()) {
1201            transitionStyle = mHost.onGetWindowAnimations();
1202        }
1203        if (transitionStyle == 0) {
1204            return null;
1205        }
1206
1207        //TypedArray attrs = mActivity.obtainStyledAttributes(transitionStyle,
1208        //        com.android.internal.R.styleable.FragmentAnimation);
1209        //int anim = attrs.getResourceId(styleIndex, 0);
1210        //attrs.recycle();
1211
1212        //if (anim == 0) {
1213        //    return null;
1214        //}
1215
1216        //return AnimatorInflater.loadAnimator(mActivity, anim);
1217        return null;
1218    }
1219
1220    public void performPendingDeferredStart(Fragment f) {
1221        if (f.mDeferStart) {
1222            if (mExecutingActions) {
1223                // Wait until we're done executing our pending transactions
1224                mHavePendingDeferredStart = true;
1225                return;
1226            }
1227            f.mDeferStart = false;
1228            moveToState(f, mCurState, 0, 0, false);
1229        }
1230    }
1231
1232    /**
1233     * Sets the to be animated view on hardware layer during the animation. Note
1234     * that calling this will replace any existing animation listener on the animation
1235     * with a new one, as animations do not support more than one listeners. Therefore,
1236     * animations that already have listeners should do the layer change operations
1237     * in their existing listeners, rather than calling this function.
1238     */
1239    private static void setHWLayerAnimListenerIfAlpha(final View v, AnimationOrAnimator anim) {
1240        if (v == null || anim == null) {
1241            return;
1242        }
1243        if (shouldRunOnHWLayer(v, anim)) {
1244            if (anim.animator != null) {
1245                anim.animator.addListener(new AnimatorOnHWLayerIfNeededListener(v));
1246            } else {
1247                AnimationListener originalListener = getAnimationListener(anim.animation);
1248                // If there's already a listener set on the animation, we need wrap the new listener
1249                // around the existing listener, so that they will both get animation listener
1250                // callbacks.
1251                v.setLayerType(View.LAYER_TYPE_HARDWARE, null);
1252                anim.animation.setAnimationListener(new AnimateOnHWLayerIfNeededListener(v,
1253                        originalListener));
1254            }
1255        }
1256    }
1257
1258    /**
1259     * Returns an existing AnimationListener on an Animation or {@code null} if none exists.
1260     */
1261    private static AnimationListener getAnimationListener(Animation animation) {
1262        AnimationListener originalListener = null;
1263        try {
1264            if (sAnimationListenerField == null) {
1265                sAnimationListenerField = Animation.class.getDeclaredField("mListener");
1266                sAnimationListenerField.setAccessible(true);
1267            }
1268            originalListener = (AnimationListener) sAnimationListenerField.get(animation);
1269        } catch (NoSuchFieldException e) {
1270            Log.e(TAG, "No field with the name mListener is found in Animation class", e);
1271        } catch (IllegalAccessException e) {
1272            Log.e(TAG, "Cannot access Animation's mListener field", e);
1273        }
1274        return originalListener;
1275    }
1276
1277    boolean isStateAtLeast(int state) {
1278        return mCurState >= state;
1279    }
1280
1281    @SuppressWarnings("ReferenceEquality")
1282    void moveToState(Fragment f, int newState, int transit, int transitionStyle,
1283            boolean keepActive) {
1284        // Fragments that are not currently added will sit in the onCreate() state.
1285        if ((!f.mAdded || f.mDetached) && newState > Fragment.CREATED) {
1286            newState = Fragment.CREATED;
1287        }
1288        if (f.mRemoving && newState > f.mState) {
1289            if (f.mState == Fragment.INITIALIZING && f.isInBackStack()) {
1290                // Allow the fragment to be created so that it can be saved later.
1291                newState = Fragment.CREATED;
1292            } else {
1293                // While removing a fragment, we can't change it to a higher state.
1294                newState = f.mState;
1295            }
1296        }
1297        // Defer start if requested; don't allow it to move to STARTED or higher
1298        // if it's not already started.
1299        if (f.mDeferStart && f.mState < Fragment.STARTED && newState > Fragment.STOPPED) {
1300            newState = Fragment.STOPPED;
1301        }
1302        if (f.mState <= newState) {
1303            // For fragments that are created from a layout, when restoring from
1304            // state we don't want to allow them to be created until they are
1305            // being reloaded from the layout.
1306            if (f.mFromLayout && !f.mInLayout) {
1307                return;
1308            }
1309            if (f.getAnimatingAway() != null || f.getAnimator() != null) {
1310                // The fragment is currently being animated...  but!  Now we
1311                // want to move our state back up.  Give up on waiting for the
1312                // animation, move to whatever the final state should be once
1313                // the animation is done, and then we can proceed from there.
1314                f.setAnimatingAway(null);
1315                f.setAnimator(null);
1316                moveToState(f, f.getStateAfterAnimating(), 0, 0, true);
1317            }
1318            switch (f.mState) {
1319                case Fragment.INITIALIZING:
1320                    if (newState > Fragment.INITIALIZING) {
1321                        if (DEBUG) Log.v(TAG, "moveto CREATED: " + f);
1322                        if (f.mSavedFragmentState != null) {
1323                            f.mSavedFragmentState.setClassLoader(mHost.getContext()
1324                                    .getClassLoader());
1325                            f.mSavedViewState = f.mSavedFragmentState.getSparseParcelableArray(
1326                                    FragmentManagerImpl.VIEW_STATE_TAG);
1327                            f.mTarget = getFragment(f.mSavedFragmentState,
1328                                    FragmentManagerImpl.TARGET_STATE_TAG);
1329                            if (f.mTarget != null) {
1330                                f.mTargetRequestCode = f.mSavedFragmentState.getInt(
1331                                        FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG, 0);
1332                            }
1333                            f.mUserVisibleHint = f.mSavedFragmentState.getBoolean(
1334                                    FragmentManagerImpl.USER_VISIBLE_HINT_TAG, true);
1335                            if (!f.mUserVisibleHint) {
1336                                f.mDeferStart = true;
1337                                if (newState > Fragment.STOPPED) {
1338                                    newState = Fragment.STOPPED;
1339                                }
1340                            }
1341                        }
1342
1343                        f.mHost = mHost;
1344                        f.mParentFragment = mParent;
1345                        f.mFragmentManager = mParent != null
1346                                ? mParent.mChildFragmentManager : mHost.getFragmentManagerImpl();
1347
1348                        // If we have a target fragment, push it along to at least CREATED
1349                        // so that this one can rely on it as an initialized dependency.
1350                        if (f.mTarget != null) {
1351                            if (mActive.get(f.mTarget.mIndex) != f.mTarget) {
1352                                throw new IllegalStateException("Fragment " + f
1353                                        + " declared target fragment " + f.mTarget
1354                                        + " that does not belong to this FragmentManager!");
1355                            }
1356                            if (f.mTarget.mState < Fragment.CREATED) {
1357                                moveToState(f.mTarget, Fragment.CREATED, 0, 0, true);
1358                            }
1359                        }
1360
1361                        dispatchOnFragmentPreAttached(f, mHost.getContext(), false);
1362                        f.mCalled = false;
1363                        f.onAttach(mHost.getContext());
1364                        if (!f.mCalled) {
1365                            throw new SuperNotCalledException("Fragment " + f
1366                                    + " did not call through to super.onAttach()");
1367                        }
1368                        if (f.mParentFragment == null) {
1369                            mHost.onAttachFragment(f);
1370                        } else {
1371                            f.mParentFragment.onAttachFragment(f);
1372                        }
1373                        dispatchOnFragmentAttached(f, mHost.getContext(), false);
1374
1375                        if (!f.mRetaining) {
1376                            dispatchOnFragmentPreCreated(f, f.mSavedFragmentState, false);
1377                            f.performCreate(f.mSavedFragmentState);
1378                            dispatchOnFragmentCreated(f, f.mSavedFragmentState, false);
1379                        } else {
1380                            f.restoreChildFragmentState(f.mSavedFragmentState);
1381                            f.mState = Fragment.CREATED;
1382                        }
1383                        f.mRetaining = false;
1384                    }
1385                    // fall through
1386                case Fragment.CREATED:
1387                    // This is outside the if statement below on purpose; we want this to run
1388                    // even if we do a moveToState from CREATED => *, CREATED => CREATED, and
1389                    // * => CREATED as part of the case fallthrough above.
1390                    ensureInflatedFragmentView(f);
1391
1392                    if (newState > Fragment.CREATED) {
1393                        if (DEBUG) Log.v(TAG, "moveto ACTIVITY_CREATED: " + f);
1394                        if (!f.mFromLayout) {
1395                            ViewGroup container = null;
1396                            if (f.mContainerId != 0) {
1397                                if (f.mContainerId == View.NO_ID) {
1398                                    throwException(new IllegalArgumentException(
1399                                            "Cannot create fragment "
1400                                                    + f
1401                                                    + " for a container view with no id"));
1402                                }
1403                                container = (ViewGroup) mContainer.onFindViewById(f.mContainerId);
1404                                if (container == null && !f.mRestored) {
1405                                    String resName;
1406                                    try {
1407                                        resName = f.getResources().getResourceName(f.mContainerId);
1408                                    } catch (NotFoundException e) {
1409                                        resName = "unknown";
1410                                    }
1411                                    throwException(new IllegalArgumentException(
1412                                            "No view found for id 0x"
1413                                            + Integer.toHexString(f.mContainerId) + " ("
1414                                            + resName
1415                                            + ") for fragment " + f));
1416                                }
1417                            }
1418                            f.mContainer = container;
1419                            f.mView = f.performCreateView(f.performGetLayoutInflater(
1420                                    f.mSavedFragmentState), container, f.mSavedFragmentState);
1421                            if (f.mView != null) {
1422                                f.mInnerView = f.mView;
1423                                f.mView.setSaveFromParentEnabled(false);
1424                                if (container != null) {
1425                                    container.addView(f.mView);
1426                                }
1427                                if (f.mHidden) {
1428                                    f.mView.setVisibility(View.GONE);
1429                                }
1430                                f.onViewCreated(f.mView, f.mSavedFragmentState);
1431                                dispatchOnFragmentViewCreated(f, f.mView, f.mSavedFragmentState,
1432                                        false);
1433                                // Only animate the view if it is visible. This is done after
1434                                // dispatchOnFragmentViewCreated in case visibility is changed
1435                                f.mIsNewlyAdded = (f.mView.getVisibility() == View.VISIBLE)
1436                                        && f.mContainer != null;
1437                            } else {
1438                                f.mInnerView = null;
1439                            }
1440                        }
1441
1442                        f.performActivityCreated(f.mSavedFragmentState);
1443                        dispatchOnFragmentActivityCreated(f, f.mSavedFragmentState, false);
1444                        if (f.mView != null) {
1445                            f.restoreViewState(f.mSavedFragmentState);
1446                        }
1447                        f.mSavedFragmentState = null;
1448                    }
1449                    // fall through
1450                case Fragment.ACTIVITY_CREATED:
1451                    if (newState > Fragment.ACTIVITY_CREATED) {
1452                        f.mState = Fragment.STOPPED;
1453                    }
1454                    // fall through
1455                case Fragment.STOPPED:
1456                    if (newState > Fragment.STOPPED) {
1457                        if (DEBUG) Log.v(TAG, "moveto STARTED: " + f);
1458                        f.performStart();
1459                        dispatchOnFragmentStarted(f, false);
1460                    }
1461                    // fall through
1462                case Fragment.STARTED:
1463                    if (newState > Fragment.STARTED) {
1464                        if (DEBUG) Log.v(TAG, "moveto RESUMED: " + f);
1465                        f.performResume();
1466                        dispatchOnFragmentResumed(f, false);
1467                        f.mSavedFragmentState = null;
1468                        f.mSavedViewState = null;
1469                    }
1470            }
1471        } else if (f.mState > newState) {
1472            switch (f.mState) {
1473                case Fragment.RESUMED:
1474                    if (newState < Fragment.RESUMED) {
1475                        if (DEBUG) Log.v(TAG, "movefrom RESUMED: " + f);
1476                        f.performPause();
1477                        dispatchOnFragmentPaused(f, false);
1478                    }
1479                    // fall through
1480                case Fragment.STARTED:
1481                    if (newState < Fragment.STARTED) {
1482                        if (DEBUG) Log.v(TAG, "movefrom STARTED: " + f);
1483                        f.performStop();
1484                        dispatchOnFragmentStopped(f, false);
1485                    }
1486                    // fall through
1487                case Fragment.STOPPED:
1488                    if (newState < Fragment.STOPPED) {
1489                        if (DEBUG) Log.v(TAG, "movefrom STOPPED: " + f);
1490                        f.performReallyStop();
1491                    }
1492                    // fall through
1493                case Fragment.ACTIVITY_CREATED:
1494                    if (newState < Fragment.ACTIVITY_CREATED) {
1495                        if (DEBUG) Log.v(TAG, "movefrom ACTIVITY_CREATED: " + f);
1496                        if (f.mView != null) {
1497                            // Need to save the current view state if not
1498                            // done already.
1499                            if (mHost.onShouldSaveFragmentState(f) && f.mSavedViewState == null) {
1500                                saveFragmentViewState(f);
1501                            }
1502                        }
1503                        f.performDestroyView();
1504                        dispatchOnFragmentViewDestroyed(f, false);
1505                        if (f.mView != null && f.mContainer != null) {
1506                            // Stop any current animations:
1507                            f.mView.clearAnimation();
1508                            f.mContainer.endViewTransition(f.mView);
1509                            AnimationOrAnimator anim = null;
1510                            if (mCurState > Fragment.INITIALIZING && !mDestroyed
1511                                    && f.mView.getVisibility() == View.VISIBLE
1512                                    && f.mPostponedAlpha >= 0) {
1513                                anim = loadAnimation(f, transit, false,
1514                                        transitionStyle);
1515                            }
1516                            f.mPostponedAlpha = 0;
1517                            if (anim != null) {
1518                                animateRemoveFragment(f, anim, newState);
1519                            }
1520                            f.mContainer.removeView(f.mView);
1521                        }
1522                        f.mContainer = null;
1523                        f.mView = null;
1524                        f.mInnerView = null;
1525                        f.mInLayout = false;
1526                    }
1527                    // fall through
1528                case Fragment.CREATED:
1529                    if (newState < Fragment.CREATED) {
1530                        if (mDestroyed) {
1531                            // The fragment's containing activity is
1532                            // being destroyed, but this fragment is
1533                            // currently animating away.  Stop the
1534                            // animation right now -- it is not needed,
1535                            // and we can't wait any more on destroying
1536                            // the fragment.
1537                            if (f.getAnimatingAway() != null) {
1538                                View v = f.getAnimatingAway();
1539                                f.setAnimatingAway(null);
1540                                v.clearAnimation();
1541                            } else if (f.getAnimator() != null) {
1542                                Animator animator = f.getAnimator();
1543                                f.setAnimator(null);
1544                                animator.cancel();
1545                            }
1546                        }
1547                        if (f.getAnimatingAway() != null || f.getAnimator() != null) {
1548                            // We are waiting for the fragment's view to finish
1549                            // animating away.  Just make a note of the state
1550                            // the fragment now should move to once the animation
1551                            // is done.
1552                            f.setStateAfterAnimating(newState);
1553                            newState = Fragment.CREATED;
1554                        } else {
1555                            if (DEBUG) Log.v(TAG, "movefrom CREATED: " + f);
1556                            if (!f.mRetaining) {
1557                                f.performDestroy();
1558                                dispatchOnFragmentDestroyed(f, false);
1559                            } else {
1560                                f.mState = Fragment.INITIALIZING;
1561                            }
1562
1563                            f.performDetach();
1564                            dispatchOnFragmentDetached(f, false);
1565                            if (!keepActive) {
1566                                if (!f.mRetaining) {
1567                                    makeInactive(f);
1568                                } else {
1569                                    f.mHost = null;
1570                                    f.mParentFragment = null;
1571                                    f.mFragmentManager = null;
1572                                }
1573                            }
1574                        }
1575                    }
1576            }
1577        }
1578
1579        if (f.mState != newState) {
1580            Log.w(TAG, "moveToState: Fragment state for " + f + " not updated inline; "
1581                    + "expected state " + newState + " found " + f.mState);
1582            f.mState = newState;
1583        }
1584    }
1585
1586    /**
1587     * Animates the removal of a fragment with the given animator or animation. After animating,
1588     * the fragment's view will be removed from the hierarchy.
1589     *
1590     * @param fragment The fragment to animate out
1591     * @param anim The animator or animation to run on the fragment's view
1592     * @param newState The final state after animating.
1593     */
1594    private void animateRemoveFragment(@NonNull final Fragment fragment,
1595            @NonNull AnimationOrAnimator anim, final int newState) {
1596        final View viewToAnimate = fragment.mView;
1597        fragment.setStateAfterAnimating(newState);
1598        if (anim.animation != null) {
1599            Animation animation = anim.animation;
1600            fragment.setAnimatingAway(fragment.mView);
1601            AnimationListener listener = getAnimationListener(animation);
1602            animation.setAnimationListener(new AnimationListenerWrapper(listener) {
1603                @Override
1604                public void onAnimationEnd(Animation animation) {
1605                    super.onAnimationEnd(animation);
1606                    if (fragment.getAnimatingAway() != null) {
1607                        fragment.setAnimatingAway(null);
1608                        moveToState(fragment, fragment.getStateAfterAnimating(), 0, 0, false);
1609                    }
1610                }
1611            });
1612            setHWLayerAnimListenerIfAlpha(viewToAnimate, anim);
1613            fragment.mView.startAnimation(animation);
1614        } else {
1615            final Animator animator = anim.animator;
1616            fragment.setAnimator(anim.animator);
1617            final ViewGroup container = fragment.mContainer;
1618            if (container != null) {
1619                container.startViewTransition(viewToAnimate);
1620            }
1621            animator.addListener(new AnimatorListenerAdapter() {
1622                @Override
1623                public void onAnimationEnd(Animator anim) {
1624                    if (container != null) {
1625                        container.endViewTransition(viewToAnimate);
1626                    }
1627                    if (fragment.getAnimator() != null) {
1628                        fragment.setAnimator(null);
1629                        moveToState(fragment, fragment.getStateAfterAnimating(), 0, 0, false);
1630                    }
1631                }
1632            });
1633            animator.setTarget(fragment.mView);
1634            setHWLayerAnimListenerIfAlpha(fragment.mView, anim);
1635            animator.start();
1636        }
1637    }
1638
1639    void moveToState(Fragment f) {
1640        moveToState(f, mCurState, 0, 0, false);
1641    }
1642
1643    void ensureInflatedFragmentView(Fragment f) {
1644        if (f.mFromLayout && !f.mPerformedCreateView) {
1645            f.mView = f.performCreateView(f.performGetLayoutInflater(
1646                    f.mSavedFragmentState), null, f.mSavedFragmentState);
1647            if (f.mView != null) {
1648                f.mInnerView = f.mView;
1649                f.mView.setSaveFromParentEnabled(false);
1650                if (f.mHidden) f.mView.setVisibility(View.GONE);
1651                f.onViewCreated(f.mView, f.mSavedFragmentState);
1652                dispatchOnFragmentViewCreated(f, f.mView, f.mSavedFragmentState, false);
1653            } else {
1654                f.mInnerView = null;
1655            }
1656        }
1657    }
1658
1659    /**
1660     * Fragments that have been shown or hidden don't have their visibility changed or
1661     * animations run during the {@link #showFragment(Fragment)} or {@link #hideFragment(Fragment)}
1662     * calls. After fragments are brought to their final state in
1663     * {@link #moveFragmentToExpectedState(Fragment)} the fragments that have been shown or
1664     * hidden must have their visibility changed and their animations started here.
1665     *
1666     * @param fragment The fragment with mHiddenChanged = true that should change its View's
1667     *                 visibility and start the show or hide animation.
1668     */
1669    void completeShowHideFragment(final Fragment fragment) {
1670        if (fragment.mView != null) {
1671            AnimationOrAnimator anim = loadAnimation(fragment, fragment.getNextTransition(),
1672                    !fragment.mHidden, fragment.getNextTransitionStyle());
1673            if (anim != null && anim.animator != null) {
1674                anim.animator.setTarget(fragment.mView);
1675                if (fragment.mHidden) {
1676                    if (fragment.isHideReplaced()) {
1677                        fragment.setHideReplaced(false);
1678                    } else {
1679                        final ViewGroup container = fragment.mContainer;
1680                        final View animatingView = fragment.mView;
1681                        container.startViewTransition(animatingView);
1682                        // Delay the actual hide operation until the animation finishes,
1683                        // otherwise the fragment will just immediately disappear
1684                        anim.animator.addListener(new AnimatorListenerAdapter() {
1685                            @Override
1686                            public void onAnimationEnd(Animator animation) {
1687                                container.endViewTransition(animatingView);
1688                                animation.removeListener(this);
1689                                if (fragment.mView != null) {
1690                                    fragment.mView.setVisibility(View.GONE);
1691                                }
1692                            }
1693                        });
1694                    }
1695                } else {
1696                    fragment.mView.setVisibility(View.VISIBLE);
1697                }
1698                setHWLayerAnimListenerIfAlpha(fragment.mView, anim);
1699                anim.animator.start();
1700            } else {
1701                if (anim != null) {
1702                    setHWLayerAnimListenerIfAlpha(fragment.mView, anim);
1703                    fragment.mView.startAnimation(anim.animation);
1704                    anim.animation.start();
1705                }
1706                final int visibility = fragment.mHidden && !fragment.isHideReplaced()
1707                        ? View.GONE
1708                        : View.VISIBLE;
1709                fragment.mView.setVisibility(visibility);
1710                if (fragment.isHideReplaced()) {
1711                    fragment.setHideReplaced(false);
1712                }
1713            }
1714        }
1715        if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) {
1716            mNeedMenuInvalidate = true;
1717        }
1718        fragment.mHiddenChanged = false;
1719        fragment.onHiddenChanged(fragment.mHidden);
1720    }
1721
1722    /**
1723     * Moves a fragment to its expected final state or the fragment manager's state, depending
1724     * on whether the fragment manager's state is raised properly.
1725     *
1726     * @param f The fragment to change.
1727     */
1728    void moveFragmentToExpectedState(Fragment f) {
1729        if (f == null) {
1730            return;
1731        }
1732        int nextState = mCurState;
1733        if (f.mRemoving) {
1734            if (f.isInBackStack()) {
1735                nextState = Math.min(nextState, Fragment.CREATED);
1736            } else {
1737                nextState = Math.min(nextState, Fragment.INITIALIZING);
1738            }
1739        }
1740        moveToState(f, nextState, f.getNextTransition(), f.getNextTransitionStyle(), false);
1741
1742        if (f.mView != null) {
1743            // Move the view if it is out of order
1744            Fragment underFragment = findFragmentUnder(f);
1745            if (underFragment != null) {
1746                final View underView = underFragment.mView;
1747                // make sure this fragment is in the right order.
1748                final ViewGroup container = f.mContainer;
1749                int underIndex = container.indexOfChild(underView);
1750                int viewIndex = container.indexOfChild(f.mView);
1751                if (viewIndex < underIndex) {
1752                    container.removeViewAt(viewIndex);
1753                    container.addView(f.mView, underIndex);
1754                }
1755            }
1756            if (f.mIsNewlyAdded && f.mContainer != null) {
1757                // Make it visible and run the animations
1758                if (f.mPostponedAlpha > 0f) {
1759                    f.mView.setAlpha(f.mPostponedAlpha);
1760                }
1761                f.mPostponedAlpha = 0f;
1762                f.mIsNewlyAdded = false;
1763                // run animations:
1764                AnimationOrAnimator anim = loadAnimation(f, f.getNextTransition(), true,
1765                        f.getNextTransitionStyle());
1766                if (anim != null) {
1767                    setHWLayerAnimListenerIfAlpha(f.mView, anim);
1768                    if (anim.animation != null) {
1769                        f.mView.startAnimation(anim.animation);
1770                    } else {
1771                        anim.animator.setTarget(f.mView);
1772                        anim.animator.start();
1773                    }
1774                }
1775            }
1776        }
1777        if (f.mHiddenChanged) {
1778            completeShowHideFragment(f);
1779        }
1780    }
1781
1782    /**
1783     * Changes the state of the fragment manager to {@code newState}. If the fragment manager
1784     * changes state or {@code always} is {@code true}, any fragments within it have their
1785     * states updated as well.
1786     *
1787     * @param newState The new state for the fragment manager
1788     * @param always If {@code true}, all fragments update their state, even
1789     *               if {@code newState} matches the current fragment manager's state.
1790     */
1791    void moveToState(int newState, boolean always) {
1792        if (mHost == null && newState != Fragment.INITIALIZING) {
1793            throw new IllegalStateException("No activity");
1794        }
1795
1796        if (!always && newState == mCurState) {
1797            return;
1798        }
1799
1800        mCurState = newState;
1801
1802        if (mActive != null) {
1803            boolean loadersRunning = false;
1804
1805            // Must add them in the proper order. mActive fragments may be out of order
1806            final int numAdded = mAdded.size();
1807            for (int i = 0; i < numAdded; i++) {
1808                Fragment f = mAdded.get(i);
1809                moveFragmentToExpectedState(f);
1810                if (f.mLoaderManager != null) {
1811                    loadersRunning |= f.mLoaderManager.hasRunningLoaders();
1812                }
1813            }
1814
1815            // Now iterate through all active fragments. These will include those that are removed
1816            // and detached.
1817            final int numActive = mActive.size();
1818            for (int i = 0; i < numActive; i++) {
1819                Fragment f = mActive.valueAt(i);
1820                if (f != null && (f.mRemoving || f.mDetached) && !f.mIsNewlyAdded) {
1821                    moveFragmentToExpectedState(f);
1822                    if (f.mLoaderManager != null) {
1823                        loadersRunning |= f.mLoaderManager.hasRunningLoaders();
1824                    }
1825                }
1826            }
1827
1828            if (!loadersRunning) {
1829                startPendingDeferredFragments();
1830            }
1831
1832            if (mNeedMenuInvalidate && mHost != null && mCurState == Fragment.RESUMED) {
1833                mHost.onSupportInvalidateOptionsMenu();
1834                mNeedMenuInvalidate = false;
1835            }
1836        }
1837    }
1838
1839    void startPendingDeferredFragments() {
1840        if (mActive == null) return;
1841
1842        for (int i=0; i<mActive.size(); i++) {
1843            Fragment f = mActive.valueAt(i);
1844            if (f != null) {
1845                performPendingDeferredStart(f);
1846            }
1847        }
1848    }
1849
1850    void makeActive(Fragment f) {
1851        if (f.mIndex >= 0) {
1852            return;
1853        }
1854
1855        f.setIndex(mNextFragmentIndex++, mParent);
1856        if (mActive == null) {
1857            mActive = new SparseArray<>();
1858        }
1859        mActive.put(f.mIndex, f);
1860        if (DEBUG) Log.v(TAG, "Allocated fragment index " + f);
1861    }
1862
1863    void makeInactive(Fragment f) {
1864        if (f.mIndex < 0) {
1865            return;
1866        }
1867
1868        if (DEBUG) Log.v(TAG, "Freeing fragment index " + f);
1869        // Don't remove yet. That happens in burpActive(). This prevents
1870        // concurrent modification while iterating over mActive
1871        mActive.put(f.mIndex, null);
1872
1873        mHost.inactivateFragment(f.mWho);
1874        f.initState();
1875    }
1876
1877    public void addFragment(Fragment fragment, boolean moveToStateNow) {
1878        if (DEBUG) Log.v(TAG, "add: " + fragment);
1879        makeActive(fragment);
1880        if (!fragment.mDetached) {
1881            if (mAdded.contains(fragment)) {
1882                throw new IllegalStateException("Fragment already added: " + fragment);
1883            }
1884            synchronized (mAdded) {
1885                mAdded.add(fragment);
1886            }
1887            fragment.mAdded = true;
1888            fragment.mRemoving = false;
1889            if (fragment.mView == null) {
1890                fragment.mHiddenChanged = false;
1891            }
1892            if (fragment.mHasMenu && fragment.mMenuVisible) {
1893                mNeedMenuInvalidate = true;
1894            }
1895            if (moveToStateNow) {
1896                moveToState(fragment);
1897            }
1898        }
1899    }
1900
1901    public void removeFragment(Fragment fragment) {
1902        if (DEBUG) Log.v(TAG, "remove: " + fragment + " nesting=" + fragment.mBackStackNesting);
1903        final boolean inactive = !fragment.isInBackStack();
1904        if (!fragment.mDetached || inactive) {
1905            synchronized (mAdded) {
1906                mAdded.remove(fragment);
1907            }
1908            if (fragment.mHasMenu && fragment.mMenuVisible) {
1909                mNeedMenuInvalidate = true;
1910            }
1911            fragment.mAdded = false;
1912            fragment.mRemoving = true;
1913        }
1914    }
1915
1916    /**
1917     * Marks a fragment as hidden to be later animated in with
1918     * {@link #completeShowHideFragment(Fragment)}.
1919     *
1920     * @param fragment The fragment to be shown.
1921     */
1922    public void hideFragment(Fragment fragment) {
1923        if (DEBUG) Log.v(TAG, "hide: " + fragment);
1924        if (!fragment.mHidden) {
1925            fragment.mHidden = true;
1926            // Toggle hidden changed so that if a fragment goes through show/hide/show
1927            // it doesn't go through the animation.
1928            fragment.mHiddenChanged = !fragment.mHiddenChanged;
1929        }
1930    }
1931
1932    /**
1933     * Marks a fragment as shown to be later animated in with
1934     * {@link #completeShowHideFragment(Fragment)}.
1935     *
1936     * @param fragment The fragment to be shown.
1937     */
1938    public void showFragment(Fragment fragment) {
1939        if (DEBUG) Log.v(TAG, "show: " + fragment);
1940        if (fragment.mHidden) {
1941            fragment.mHidden = false;
1942            // Toggle hidden changed so that if a fragment goes through show/hide/show
1943            // it doesn't go through the animation.
1944            fragment.mHiddenChanged = !fragment.mHiddenChanged;
1945        }
1946    }
1947
1948    public void detachFragment(Fragment fragment) {
1949        if (DEBUG) Log.v(TAG, "detach: " + fragment);
1950        if (!fragment.mDetached) {
1951            fragment.mDetached = true;
1952            if (fragment.mAdded) {
1953                // We are not already in back stack, so need to remove the fragment.
1954                if (DEBUG) Log.v(TAG, "remove from detach: " + fragment);
1955                synchronized (mAdded) {
1956                    mAdded.remove(fragment);
1957                }
1958                if (fragment.mHasMenu && fragment.mMenuVisible) {
1959                    mNeedMenuInvalidate = true;
1960                }
1961                fragment.mAdded = false;
1962            }
1963        }
1964    }
1965
1966    public void attachFragment(Fragment fragment) {
1967        if (DEBUG) Log.v(TAG, "attach: " + fragment);
1968        if (fragment.mDetached) {
1969            fragment.mDetached = false;
1970            if (!fragment.mAdded) {
1971                if (mAdded.contains(fragment)) {
1972                    throw new IllegalStateException("Fragment already added: " + fragment);
1973                }
1974                if (DEBUG) Log.v(TAG, "add from attach: " + fragment);
1975                synchronized (mAdded) {
1976                    mAdded.add(fragment);
1977                }
1978                fragment.mAdded = true;
1979                if (fragment.mHasMenu && fragment.mMenuVisible) {
1980                    mNeedMenuInvalidate = true;
1981                }
1982            }
1983        }
1984    }
1985
1986    @Override
1987    public Fragment findFragmentById(int id) {
1988        // First look through added fragments.
1989        for (int i = mAdded.size() - 1; i >= 0; i--) {
1990            Fragment f = mAdded.get(i);
1991            if (f != null && f.mFragmentId == id) {
1992                return f;
1993            }
1994        }
1995        if (mActive != null) {
1996            // Now for any known fragment.
1997            for (int i=mActive.size()-1; i>=0; i--) {
1998                Fragment f = mActive.valueAt(i);
1999                if (f != null && f.mFragmentId == id) {
2000                    return f;
2001                }
2002            }
2003        }
2004        return null;
2005    }
2006
2007    @Override
2008    public Fragment findFragmentByTag(String tag) {
2009        if (tag != null) {
2010            // First look through added fragments.
2011            for (int i=mAdded.size()-1; i>=0; i--) {
2012                Fragment f = mAdded.get(i);
2013                if (f != null && tag.equals(f.mTag)) {
2014                    return f;
2015                }
2016            }
2017        }
2018        if (mActive != null && tag != null) {
2019            // Now for any known fragment.
2020            for (int i=mActive.size()-1; i>=0; i--) {
2021                Fragment f = mActive.valueAt(i);
2022                if (f != null && tag.equals(f.mTag)) {
2023                    return f;
2024                }
2025            }
2026        }
2027        return null;
2028    }
2029
2030    public Fragment findFragmentByWho(String who) {
2031        if (mActive != null && who != null) {
2032            for (int i=mActive.size()-1; i>=0; i--) {
2033                Fragment f = mActive.valueAt(i);
2034                if (f != null && (f=f.findFragmentByWho(who)) != null) {
2035                    return f;
2036                }
2037            }
2038        }
2039        return null;
2040    }
2041
2042    private void checkStateLoss() {
2043        if (mStateSaved) {
2044            throw new IllegalStateException(
2045                    "Can not perform this action after onSaveInstanceState");
2046        }
2047        if (mNoTransactionsBecause != null) {
2048            throw new IllegalStateException(
2049                    "Can not perform this action inside of " + mNoTransactionsBecause);
2050        }
2051    }
2052
2053    @Override
2054    public boolean isStateSaved() {
2055        return mStateSaved;
2056    }
2057
2058    /**
2059     * Adds an action to the queue of pending actions.
2060     *
2061     * @param action the action to add
2062     * @param allowStateLoss whether to allow loss of state information
2063     * @throws IllegalStateException if the activity has been destroyed
2064     */
2065    public void enqueueAction(OpGenerator action, boolean allowStateLoss) {
2066        if (!allowStateLoss) {
2067            checkStateLoss();
2068        }
2069        synchronized (this) {
2070            if (mDestroyed || mHost == null) {
2071                if (allowStateLoss) {
2072                    // This FragmentManager isn't attached, so drop the entire transaction.
2073                    return;
2074                }
2075                throw new IllegalStateException("Activity has been destroyed");
2076            }
2077            if (mPendingActions == null) {
2078                mPendingActions = new ArrayList<>();
2079            }
2080            mPendingActions.add(action);
2081            scheduleCommit();
2082        }
2083    }
2084
2085    /**
2086     * Schedules the execution when one hasn't been scheduled already. This should happen
2087     * the first time {@link #enqueueAction(OpGenerator, boolean)} is called or when
2088     * a postponed transaction has been started with
2089     * {@link Fragment#startPostponedEnterTransition()}
2090     */
2091    private void scheduleCommit() {
2092        synchronized (this) {
2093            boolean postponeReady =
2094                    mPostponedTransactions != null && !mPostponedTransactions.isEmpty();
2095            boolean pendingReady = mPendingActions != null && mPendingActions.size() == 1;
2096            if (postponeReady || pendingReady) {
2097                mHost.getHandler().removeCallbacks(mExecCommit);
2098                mHost.getHandler().post(mExecCommit);
2099            }
2100        }
2101    }
2102
2103    public int allocBackStackIndex(BackStackRecord bse) {
2104        synchronized (this) {
2105            if (mAvailBackStackIndices == null || mAvailBackStackIndices.size() <= 0) {
2106                if (mBackStackIndices == null) {
2107                    mBackStackIndices = new ArrayList<BackStackRecord>();
2108                }
2109                int index = mBackStackIndices.size();
2110                if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse);
2111                mBackStackIndices.add(bse);
2112                return index;
2113
2114            } else {
2115                int index = mAvailBackStackIndices.remove(mAvailBackStackIndices.size()-1);
2116                if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse);
2117                mBackStackIndices.set(index, bse);
2118                return index;
2119            }
2120        }
2121    }
2122
2123    public void setBackStackIndex(int index, BackStackRecord bse) {
2124        synchronized (this) {
2125            if (mBackStackIndices == null) {
2126                mBackStackIndices = new ArrayList<BackStackRecord>();
2127            }
2128            int N = mBackStackIndices.size();
2129            if (index < N) {
2130                if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse);
2131                mBackStackIndices.set(index, bse);
2132            } else {
2133                while (N < index) {
2134                    mBackStackIndices.add(null);
2135                    if (mAvailBackStackIndices == null) {
2136                        mAvailBackStackIndices = new ArrayList<Integer>();
2137                    }
2138                    if (DEBUG) Log.v(TAG, "Adding available back stack index " + N);
2139                    mAvailBackStackIndices.add(N);
2140                    N++;
2141                }
2142                if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse);
2143                mBackStackIndices.add(bse);
2144            }
2145        }
2146    }
2147
2148    public void freeBackStackIndex(int index) {
2149        synchronized (this) {
2150            mBackStackIndices.set(index, null);
2151            if (mAvailBackStackIndices == null) {
2152                mAvailBackStackIndices = new ArrayList<Integer>();
2153            }
2154            if (DEBUG) Log.v(TAG, "Freeing back stack index " + index);
2155            mAvailBackStackIndices.add(index);
2156        }
2157    }
2158
2159    /**
2160     * Broken out from exec*, this prepares for gathering and executing operations.
2161     *
2162     * @param allowStateLoss true if state loss should be ignored or false if it should be
2163     *                       checked.
2164     */
2165    private void ensureExecReady(boolean allowStateLoss) {
2166        if (mExecutingActions) {
2167            throw new IllegalStateException("FragmentManager is already executing transactions");
2168        }
2169
2170        if (Looper.myLooper() != mHost.getHandler().getLooper()) {
2171            throw new IllegalStateException("Must be called from main thread of fragment host");
2172        }
2173
2174        if (!allowStateLoss) {
2175            checkStateLoss();
2176        }
2177
2178        if (mTmpRecords == null) {
2179            mTmpRecords = new ArrayList<>();
2180            mTmpIsPop = new ArrayList<>();
2181        }
2182        mExecutingActions = true;
2183        try {
2184            executePostponedTransaction(null, null);
2185        } finally {
2186            mExecutingActions = false;
2187        }
2188    }
2189
2190    public void execSingleAction(OpGenerator action, boolean allowStateLoss) {
2191        if (allowStateLoss && (mHost == null || mDestroyed)) {
2192            // This FragmentManager isn't attached, so drop the entire transaction.
2193            return;
2194        }
2195        ensureExecReady(allowStateLoss);
2196        if (action.generateOps(mTmpRecords, mTmpIsPop)) {
2197            mExecutingActions = true;
2198            try {
2199                removeRedundantOperationsAndExecute(mTmpRecords, mTmpIsPop);
2200            } finally {
2201                cleanupExec();
2202            }
2203        }
2204
2205        doPendingDeferredStart();
2206        burpActive();
2207    }
2208
2209    /**
2210     * Broken out of exec*, this cleans up the mExecutingActions and the temporary structures
2211     * used in executing operations.
2212     */
2213    private void cleanupExec() {
2214        mExecutingActions = false;
2215        mTmpIsPop.clear();
2216        mTmpRecords.clear();
2217    }
2218
2219    /**
2220     * Only call from main thread!
2221     */
2222    public boolean execPendingActions() {
2223        ensureExecReady(true);
2224
2225        boolean didSomething = false;
2226        while (generateOpsForPendingActions(mTmpRecords, mTmpIsPop)) {
2227            mExecutingActions = true;
2228            try {
2229                removeRedundantOperationsAndExecute(mTmpRecords, mTmpIsPop);
2230            } finally {
2231                cleanupExec();
2232            }
2233            didSomething = true;
2234        }
2235
2236        doPendingDeferredStart();
2237        burpActive();
2238
2239        return didSomething;
2240    }
2241
2242    /**
2243     * Complete the execution of transactions that have previously been postponed, but are
2244     * now ready.
2245     */
2246    private void executePostponedTransaction(ArrayList<BackStackRecord> records,
2247            ArrayList<Boolean> isRecordPop) {
2248        int numPostponed = mPostponedTransactions == null ? 0 : mPostponedTransactions.size();
2249        for (int i = 0; i < numPostponed; i++) {
2250            StartEnterTransitionListener listener = mPostponedTransactions.get(i);
2251            if (records != null && !listener.mIsBack) {
2252                int index = records.indexOf(listener.mRecord);
2253                if (index != -1 && isRecordPop.get(index)) {
2254                    listener.cancelTransaction();
2255                    continue;
2256                }
2257            }
2258            if (listener.isReady() || (records != null
2259                    && listener.mRecord.interactsWith(records, 0, records.size()))) {
2260                mPostponedTransactions.remove(i);
2261                i--;
2262                numPostponed--;
2263                int index;
2264                if (records != null && !listener.mIsBack
2265                        && (index = records.indexOf(listener.mRecord)) != -1
2266                        && isRecordPop.get(index)) {
2267                    // This is popping a postponed transaction
2268                    listener.cancelTransaction();
2269                } else {
2270                    listener.completeTransaction();
2271                }
2272            }
2273        }
2274    }
2275
2276    /**
2277     * Remove redundant BackStackRecord operations and executes them. This method merges operations
2278     * of proximate records that allow reordering. See
2279     * {@link FragmentTransaction#setReorderingAllowed(boolean)}.
2280     * <p>
2281     * For example, a transaction that adds to the back stack and then another that pops that
2282     * back stack record will be optimized to remove the unnecessary operation.
2283     * <p>
2284     * Likewise, two transactions committed that are executed at the same time will be optimized
2285     * to remove the redundant operations as well as two pop operations executed together.
2286     *
2287     * @param records The records pending execution
2288     * @param isRecordPop The direction that these records are being run.
2289     */
2290    private void removeRedundantOperationsAndExecute(ArrayList<BackStackRecord> records,
2291            ArrayList<Boolean> isRecordPop) {
2292        if (records == null || records.isEmpty()) {
2293            return;
2294        }
2295
2296        if (isRecordPop == null || records.size() != isRecordPop.size()) {
2297            throw new IllegalStateException("Internal error with the back stack records");
2298        }
2299
2300        // Force start of any postponed transactions that interact with scheduled transactions:
2301        executePostponedTransaction(records, isRecordPop);
2302
2303        final int numRecords = records.size();
2304        int startIndex = 0;
2305        for (int recordNum = 0; recordNum < numRecords; recordNum++) {
2306            final boolean canReorder = records.get(recordNum).mReorderingAllowed;
2307            if (!canReorder) {
2308                // execute all previous transactions
2309                if (startIndex != recordNum) {
2310                    executeOpsTogether(records, isRecordPop, startIndex, recordNum);
2311                }
2312                // execute all pop operations that don't allow reordering together or
2313                // one add operation
2314                int reorderingEnd = recordNum + 1;
2315                if (isRecordPop.get(recordNum)) {
2316                    while (reorderingEnd < numRecords
2317                            && isRecordPop.get(reorderingEnd)
2318                            && !records.get(reorderingEnd).mReorderingAllowed) {
2319                        reorderingEnd++;
2320                    }
2321                }
2322                executeOpsTogether(records, isRecordPop, recordNum, reorderingEnd);
2323                startIndex = reorderingEnd;
2324                recordNum = reorderingEnd - 1;
2325            }
2326        }
2327        if (startIndex != numRecords) {
2328            executeOpsTogether(records, isRecordPop, startIndex, numRecords);
2329        }
2330    }
2331
2332    /**
2333     * Executes a subset of a list of BackStackRecords, all of which either allow reordering or
2334     * do not allow ordering.
2335     * @param records A list of BackStackRecords that are to be executed
2336     * @param isRecordPop The direction that these records are being run.
2337     * @param startIndex The index of the first record in <code>records</code> to be executed
2338     * @param endIndex One more than the final record index in <code>records</code> to executed.
2339     */
2340    private void executeOpsTogether(ArrayList<BackStackRecord> records,
2341            ArrayList<Boolean> isRecordPop, int startIndex, int endIndex) {
2342        final boolean allowReordering = records.get(startIndex).mReorderingAllowed;
2343        boolean addToBackStack = false;
2344        if (mTmpAddedFragments == null) {
2345            mTmpAddedFragments = new ArrayList<>();
2346        } else {
2347            mTmpAddedFragments.clear();
2348        }
2349        mTmpAddedFragments.addAll(mAdded);
2350        Fragment oldPrimaryNav = getPrimaryNavigationFragment();
2351        for (int recordNum = startIndex; recordNum < endIndex; recordNum++) {
2352            final BackStackRecord record = records.get(recordNum);
2353            final boolean isPop = isRecordPop.get(recordNum);
2354            if (!isPop) {
2355                oldPrimaryNav = record.expandOps(mTmpAddedFragments, oldPrimaryNav);
2356            } else {
2357                oldPrimaryNav = record.trackAddedFragmentsInPop(mTmpAddedFragments, oldPrimaryNav);
2358            }
2359            addToBackStack = addToBackStack || record.mAddToBackStack;
2360        }
2361        mTmpAddedFragments.clear();
2362
2363        if (!allowReordering) {
2364            FragmentTransition.startTransitions(this, records, isRecordPop, startIndex, endIndex,
2365                    false);
2366        }
2367        executeOps(records, isRecordPop, startIndex, endIndex);
2368
2369        int postponeIndex = endIndex;
2370        if (allowReordering) {
2371            ArraySet<Fragment> addedFragments = new ArraySet<>();
2372            addAddedFragments(addedFragments);
2373            postponeIndex = postponePostponableTransactions(records, isRecordPop,
2374                    startIndex, endIndex, addedFragments);
2375            makeRemovedFragmentsInvisible(addedFragments);
2376        }
2377
2378        if (postponeIndex != startIndex && allowReordering) {
2379            // need to run something now
2380            FragmentTransition.startTransitions(this, records, isRecordPop, startIndex,
2381                    postponeIndex, true);
2382            moveToState(mCurState, true);
2383        }
2384
2385        for (int recordNum = startIndex; recordNum < endIndex; recordNum++) {
2386            final BackStackRecord record = records.get(recordNum);
2387            final boolean isPop = isRecordPop.get(recordNum);
2388            if (isPop && record.mIndex >= 0) {
2389                freeBackStackIndex(record.mIndex);
2390                record.mIndex = -1;
2391            }
2392            record.runOnCommitRunnables();
2393        }
2394        if (addToBackStack) {
2395            reportBackStackChanged();
2396        }
2397    }
2398
2399    /**
2400     * Any fragments that were removed because they have been postponed should have their views
2401     * made invisible by setting their alpha to 0.
2402     *
2403     * @param fragments The fragments that were added during operation execution. Only the ones
2404     *                  that are no longer added will have their alpha changed.
2405     */
2406    private void makeRemovedFragmentsInvisible(ArraySet<Fragment> fragments) {
2407        final int numAdded = fragments.size();
2408        for (int i = 0; i < numAdded; i++) {
2409            final Fragment fragment = fragments.valueAt(i);
2410            if (!fragment.mAdded) {
2411                final View view = fragment.getView();
2412                fragment.mPostponedAlpha = view.getAlpha();
2413                view.setAlpha(0f);
2414            }
2415        }
2416    }
2417
2418    /**
2419     * Examine all transactions and determine which ones are marked as postponed. Those will
2420     * have their operations rolled back and moved to the end of the record list (up to endIndex).
2421     * It will also add the postponed transaction to the queue.
2422     *
2423     * @param records A list of BackStackRecords that should be checked.
2424     * @param isRecordPop The direction that these records are being run.
2425     * @param startIndex The index of the first record in <code>records</code> to be checked
2426     * @param endIndex One more than the final record index in <code>records</code> to be checked.
2427     * @return The index of the first postponed transaction or endIndex if no transaction was
2428     * postponed.
2429     */
2430    private int postponePostponableTransactions(ArrayList<BackStackRecord> records,
2431            ArrayList<Boolean> isRecordPop, int startIndex, int endIndex,
2432            ArraySet<Fragment> added) {
2433        int postponeIndex = endIndex;
2434        for (int i = endIndex - 1; i >= startIndex; i--) {
2435            final BackStackRecord record = records.get(i);
2436            final boolean isPop = isRecordPop.get(i);
2437            boolean isPostponed = record.isPostponed()
2438                    && !record.interactsWith(records, i + 1, endIndex);
2439            if (isPostponed) {
2440                if (mPostponedTransactions == null) {
2441                    mPostponedTransactions = new ArrayList<>();
2442                }
2443                StartEnterTransitionListener listener =
2444                        new StartEnterTransitionListener(record, isPop);
2445                mPostponedTransactions.add(listener);
2446                record.setOnStartPostponedListener(listener);
2447
2448                // roll back the transaction
2449                if (isPop) {
2450                    record.executeOps();
2451                } else {
2452                    record.executePopOps(false);
2453                }
2454
2455                // move to the end
2456                postponeIndex--;
2457                if (i != postponeIndex) {
2458                    records.remove(i);
2459                    records.add(postponeIndex, record);
2460                }
2461
2462                // different views may be visible now
2463                addAddedFragments(added);
2464            }
2465        }
2466        return postponeIndex;
2467    }
2468
2469    /**
2470     * When a postponed transaction is ready to be started, this completes the transaction,
2471     * removing, hiding, or showing views as well as starting the animations and transitions.
2472     * <p>
2473     * {@code runtransitions} is set to false when the transaction postponement was interrupted
2474     * abnormally -- normally by a new transaction being started that affects the postponed
2475     * transaction.
2476     *
2477     * @param record The transaction to run
2478     * @param isPop true if record is popping or false if it is adding
2479     * @param runTransitions true if the fragment transition should be run or false otherwise.
2480     * @param moveToState true if the state should be changed after executing the operations.
2481     *                    This is false when the transaction is canceled when a postponed
2482     *                    transaction is popped.
2483     */
2484    private void completeExecute(BackStackRecord record, boolean isPop, boolean runTransitions,
2485            boolean moveToState) {
2486        if (isPop) {
2487            record.executePopOps(moveToState);
2488        } else {
2489            record.executeOps();
2490        }
2491        ArrayList<BackStackRecord> records = new ArrayList<>(1);
2492        ArrayList<Boolean> isRecordPop = new ArrayList<>(1);
2493        records.add(record);
2494        isRecordPop.add(isPop);
2495        if (runTransitions) {
2496            FragmentTransition.startTransitions(this, records, isRecordPop, 0, 1, true);
2497        }
2498        if (moveToState) {
2499            moveToState(mCurState, true);
2500        }
2501
2502        if (mActive != null) {
2503            final int numActive = mActive.size();
2504            for (int i = 0; i < numActive; i++) {
2505                // Allow added fragments to be removed during the pop since we aren't going
2506                // to move them to the final state with moveToState(mCurState).
2507                Fragment fragment = mActive.valueAt(i);
2508                if (fragment != null && fragment.mView != null && fragment.mIsNewlyAdded
2509                        && record.interactsWith(fragment.mContainerId)) {
2510                    if (fragment.mPostponedAlpha > 0) {
2511                        fragment.mView.setAlpha(fragment.mPostponedAlpha);
2512                    }
2513                    if (moveToState) {
2514                        fragment.mPostponedAlpha = 0;
2515                    } else {
2516                        fragment.mPostponedAlpha = -1;
2517                        fragment.mIsNewlyAdded = false;
2518                    }
2519                }
2520            }
2521        }
2522    }
2523
2524    /**
2525     * Find a fragment within the fragment's container whose View should be below the passed
2526     * fragment. {@code null} is returned when the fragment has no View or if there should be
2527     * no fragment with a View below the given fragment.
2528     *
2529     * As an example, if mAdded has two Fragments with Views sharing the same container:
2530     * FragmentA
2531     * FragmentB
2532     *
2533     * Then, when processing FragmentB, FragmentA will be returned. If, however, FragmentA
2534     * had no View, null would be returned.
2535     *
2536     * @param f The fragment that may be on top of another fragment.
2537     * @return The fragment with a View under f, if one exists or null if f has no View or
2538     * there are no fragments with Views in the same container.
2539     */
2540    private Fragment findFragmentUnder(Fragment f) {
2541        final ViewGroup container = f.mContainer;
2542        final View view = f.mView;
2543
2544        if (container == null || view == null) {
2545            return null;
2546        }
2547
2548        final int fragmentIndex = mAdded.indexOf(f);
2549        for (int i = fragmentIndex - 1; i >= 0; i--) {
2550            Fragment underFragment = mAdded.get(i);
2551            if (underFragment.mContainer == container && underFragment.mView != null) {
2552                // Found the fragment under this one
2553                return underFragment;
2554            }
2555        }
2556        return null;
2557    }
2558
2559    /**
2560     * Run the operations in the BackStackRecords, either to push or pop.
2561     *
2562     * @param records The list of records whose operations should be run.
2563     * @param isRecordPop The direction that these records are being run.
2564     * @param startIndex The index of the first entry in records to run.
2565     * @param endIndex One past the index of the final entry in records to run.
2566     */
2567    private static void executeOps(ArrayList<BackStackRecord> records,
2568            ArrayList<Boolean> isRecordPop, int startIndex, int endIndex) {
2569        for (int i = startIndex; i < endIndex; i++) {
2570            final BackStackRecord record = records.get(i);
2571            final boolean isPop = isRecordPop.get(i);
2572            if (isPop) {
2573                record.bumpBackStackNesting(-1);
2574                // Only execute the add operations at the end of
2575                // all transactions.
2576                boolean moveToState = i == (endIndex - 1);
2577                record.executePopOps(moveToState);
2578            } else {
2579                record.bumpBackStackNesting(1);
2580                record.executeOps();
2581            }
2582        }
2583    }
2584
2585    /**
2586     * Ensure that fragments that are added are moved to at least the CREATED state.
2587     * Any newly-added Views are inserted into {@code added} so that the Transaction can be
2588     * postponed with {@link Fragment#postponeEnterTransition()}. They will later be made
2589     * invisible (by setting their alpha to 0) if they have been removed when postponed.
2590     */
2591    private void addAddedFragments(ArraySet<Fragment> added) {
2592        if (mCurState < Fragment.CREATED) {
2593            return;
2594        }
2595        // We want to leave the fragment in the started state
2596        final int state = Math.min(mCurState, Fragment.STARTED);
2597        final int numAdded = mAdded.size();
2598        for (int i = 0; i < numAdded; i++) {
2599            Fragment fragment = mAdded.get(i);
2600            if (fragment.mState < state) {
2601                moveToState(fragment, state, fragment.getNextAnim(), fragment.getNextTransition(),
2602                        false);
2603                if (fragment.mView != null && !fragment.mHidden && fragment.mIsNewlyAdded) {
2604                    added.add(fragment);
2605                }
2606            }
2607        }
2608    }
2609
2610    /**
2611     * Starts all postponed transactions regardless of whether they are ready or not.
2612     */
2613    private void forcePostponedTransactions() {
2614        if (mPostponedTransactions != null) {
2615            while (!mPostponedTransactions.isEmpty()) {
2616                mPostponedTransactions.remove(0).completeTransaction();
2617            }
2618        }
2619    }
2620
2621    /**
2622     * Ends the animations of fragments so that they immediately reach the end state.
2623     * This is used prior to saving the state so that the correct state is saved.
2624     */
2625    private void endAnimatingAwayFragments() {
2626        final int numFragments = mActive == null ? 0 : mActive.size();
2627        for (int i = 0; i < numFragments; i++) {
2628            Fragment fragment = mActive.valueAt(i);
2629            if (fragment != null) {
2630                if (fragment.getAnimatingAway() != null) {
2631                    // Give up waiting for the animation and just end it.
2632                    final int stateAfterAnimating = fragment.getStateAfterAnimating();
2633                    final View animatingAway = fragment.getAnimatingAway();
2634                    fragment.setAnimatingAway(null);
2635                    Animation animation = animatingAway.getAnimation();
2636                    if (animation != null) {
2637                        animation.cancel();
2638                        // force-clear the animation, as Animation#cancel() doesn't work prior to N,
2639                        // and will instead cause the animation to infinitely loop
2640                        animatingAway.clearAnimation();
2641                    }
2642                    moveToState(fragment, stateAfterAnimating, 0, 0, false);
2643                } else if (fragment.getAnimator() != null) {
2644                    fragment.getAnimator().end();
2645                }
2646            }
2647        }
2648    }
2649
2650    /**
2651     * Adds all records in the pending actions to records and whether they are add or pop
2652     * operations to isPop. After executing, the pending actions will be empty.
2653     *
2654     * @param records All pending actions will generate BackStackRecords added to this.
2655     *                This contains the transactions, in order, to execute.
2656     * @param isPop All pending actions will generate booleans to add to this. This contains
2657     *              an entry for each entry in records to indicate whether or not it is a
2658     *              pop action.
2659     */
2660    private boolean generateOpsForPendingActions(ArrayList<BackStackRecord> records,
2661            ArrayList<Boolean> isPop) {
2662        boolean didSomething = false;
2663        synchronized (this) {
2664            if (mPendingActions == null || mPendingActions.size() == 0) {
2665                return false;
2666            }
2667
2668            final int numActions = mPendingActions.size();
2669            for (int i = 0; i < numActions; i++) {
2670                didSomething |= mPendingActions.get(i).generateOps(records, isPop);
2671            }
2672            mPendingActions.clear();
2673            mHost.getHandler().removeCallbacks(mExecCommit);
2674        }
2675        return didSomething;
2676    }
2677
2678    void doPendingDeferredStart() {
2679        if (mHavePendingDeferredStart) {
2680            boolean loadersRunning = false;
2681            for (int i = 0; i < mActive.size(); i++) {
2682                Fragment f = mActive.valueAt(i);
2683                if (f != null && f.mLoaderManager != null) {
2684                    loadersRunning |= f.mLoaderManager.hasRunningLoaders();
2685                }
2686            }
2687            if (!loadersRunning) {
2688                mHavePendingDeferredStart = false;
2689                startPendingDeferredFragments();
2690            }
2691        }
2692    }
2693
2694    void reportBackStackChanged() {
2695        if (mBackStackChangeListeners != null) {
2696            for (int i=0; i<mBackStackChangeListeners.size(); i++) {
2697                mBackStackChangeListeners.get(i).onBackStackChanged();
2698            }
2699        }
2700    }
2701
2702    void addBackStackState(BackStackRecord state) {
2703        if (mBackStack == null) {
2704            mBackStack = new ArrayList<BackStackRecord>();
2705        }
2706        mBackStack.add(state);
2707    }
2708
2709    @SuppressWarnings("unused")
2710    boolean popBackStackState(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop,
2711            String name, int id, int flags) {
2712        if (mBackStack == null) {
2713            return false;
2714        }
2715        if (name == null && id < 0 && (flags & POP_BACK_STACK_INCLUSIVE) == 0) {
2716            int last = mBackStack.size() - 1;
2717            if (last < 0) {
2718                return false;
2719            }
2720            records.add(mBackStack.remove(last));
2721            isRecordPop.add(true);
2722        } else {
2723            int index = -1;
2724            if (name != null || id >= 0) {
2725                // If a name or ID is specified, look for that place in
2726                // the stack.
2727                index = mBackStack.size()-1;
2728                while (index >= 0) {
2729                    BackStackRecord bss = mBackStack.get(index);
2730                    if (name != null && name.equals(bss.getName())) {
2731                        break;
2732                    }
2733                    if (id >= 0 && id == bss.mIndex) {
2734                        break;
2735                    }
2736                    index--;
2737                }
2738                if (index < 0) {
2739                    return false;
2740                }
2741                if ((flags&POP_BACK_STACK_INCLUSIVE) != 0) {
2742                    index--;
2743                    // Consume all following entries that match.
2744                    while (index >= 0) {
2745                        BackStackRecord bss = mBackStack.get(index);
2746                        if ((name != null && name.equals(bss.getName()))
2747                                || (id >= 0 && id == bss.mIndex)) {
2748                            index--;
2749                            continue;
2750                        }
2751                        break;
2752                    }
2753                }
2754            }
2755            if (index == mBackStack.size()-1) {
2756                return false;
2757            }
2758            for (int i = mBackStack.size() - 1; i > index; i--) {
2759                records.add(mBackStack.remove(i));
2760                isRecordPop.add(true);
2761            }
2762        }
2763        return true;
2764    }
2765
2766    FragmentManagerNonConfig retainNonConfig() {
2767        setRetaining(mSavedNonConfig);
2768        return mSavedNonConfig;
2769    }
2770
2771    /**
2772     * Recurse the FragmentManagerNonConfig fragments and set the mRetaining to true. This
2773     * was previously done while saving the non-config state, but that has been moved to
2774     * {@link #saveNonConfig()} called from {@link #saveAllState()}. If mRetaining is set too
2775     * early, the fragment won't be destroyed when the FragmentManager is destroyed.
2776     */
2777    private static void setRetaining(FragmentManagerNonConfig nonConfig) {
2778        if (nonConfig == null) {
2779            return;
2780        }
2781        List<Fragment> fragments = nonConfig.getFragments();
2782        if (fragments != null) {
2783            for (Fragment fragment : fragments) {
2784                fragment.mRetaining = true;
2785            }
2786        }
2787        List<FragmentManagerNonConfig> children = nonConfig.getChildNonConfigs();
2788        if (children != null) {
2789            for (FragmentManagerNonConfig child : children) {
2790                setRetaining(child);
2791            }
2792        }
2793    }
2794
2795    void saveNonConfig() {
2796        ArrayList<Fragment> fragments = null;
2797        ArrayList<FragmentManagerNonConfig> childFragments = null;
2798        if (mActive != null) {
2799            for (int i=0; i<mActive.size(); i++) {
2800                Fragment f = mActive.valueAt(i);
2801                if (f != null) {
2802                    if (f.mRetainInstance) {
2803                        if (fragments == null) {
2804                            fragments = new ArrayList<Fragment>();
2805                        }
2806                        fragments.add(f);
2807                        f.mTargetIndex = f.mTarget != null ? f.mTarget.mIndex : -1;
2808                        if (DEBUG) Log.v(TAG, "retainNonConfig: keeping retained " + f);
2809                    }
2810                    FragmentManagerNonConfig child;
2811                    if (f.mChildFragmentManager != null) {
2812                        f.mChildFragmentManager.saveNonConfig();
2813                        child = f.mChildFragmentManager.mSavedNonConfig;
2814                    } else {
2815                        // f.mChildNonConfig may be not null, when the parent fragment is
2816                        // in the backstack.
2817                        child = f.mChildNonConfig;
2818                    }
2819
2820                    if (childFragments == null && child != null) {
2821                        childFragments = new ArrayList<>(mActive.size());
2822                        for (int j = 0; j < i; j++) {
2823                            childFragments.add(null);
2824                        }
2825                    }
2826
2827                    if (childFragments != null) {
2828                        childFragments.add(child);
2829                    }
2830                }
2831            }
2832        }
2833        if (fragments == null && childFragments == null) {
2834            mSavedNonConfig = null;
2835        } else {
2836            mSavedNonConfig = new FragmentManagerNonConfig(fragments, childFragments);
2837        }
2838    }
2839
2840    void saveFragmentViewState(Fragment f) {
2841        if (f.mInnerView == null) {
2842            return;
2843        }
2844        if (mStateArray == null) {
2845            mStateArray = new SparseArray<Parcelable>();
2846        } else {
2847            mStateArray.clear();
2848        }
2849        f.mInnerView.saveHierarchyState(mStateArray);
2850        if (mStateArray.size() > 0) {
2851            f.mSavedViewState = mStateArray;
2852            mStateArray = null;
2853        }
2854    }
2855
2856    Bundle saveFragmentBasicState(Fragment f) {
2857        Bundle result = null;
2858
2859        if (mStateBundle == null) {
2860            mStateBundle = new Bundle();
2861        }
2862        f.performSaveInstanceState(mStateBundle);
2863        dispatchOnFragmentSaveInstanceState(f, mStateBundle, false);
2864        if (!mStateBundle.isEmpty()) {
2865            result = mStateBundle;
2866            mStateBundle = null;
2867        }
2868
2869        if (f.mView != null) {
2870            saveFragmentViewState(f);
2871        }
2872        if (f.mSavedViewState != null) {
2873            if (result == null) {
2874                result = new Bundle();
2875            }
2876            result.putSparseParcelableArray(
2877                    FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState);
2878        }
2879        if (!f.mUserVisibleHint) {
2880            if (result == null) {
2881                result = new Bundle();
2882            }
2883            // Only add this if it's not the default value
2884            result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint);
2885        }
2886
2887        return result;
2888    }
2889
2890    Parcelable saveAllState() {
2891        // Make sure all pending operations have now been executed to get
2892        // our state update-to-date.
2893        forcePostponedTransactions();
2894        endAnimatingAwayFragments();
2895        execPendingActions();
2896
2897        mStateSaved = true;
2898        mSavedNonConfig = null;
2899
2900        if (mActive == null || mActive.size() <= 0) {
2901            return null;
2902        }
2903
2904        // First collect all active fragments.
2905        int N = mActive.size();
2906        FragmentState[] active = new FragmentState[N];
2907        boolean haveFragments = false;
2908        for (int i=0; i<N; i++) {
2909            Fragment f = mActive.valueAt(i);
2910            if (f != null) {
2911                if (f.mIndex < 0) {
2912                    throwException(new IllegalStateException(
2913                            "Failure saving state: active " + f
2914                            + " has cleared index: " + f.mIndex));
2915                }
2916
2917                haveFragments = true;
2918
2919                FragmentState fs = new FragmentState(f);
2920                active[i] = fs;
2921
2922                if (f.mState > Fragment.INITIALIZING && fs.mSavedFragmentState == null) {
2923                    fs.mSavedFragmentState = saveFragmentBasicState(f);
2924
2925                    if (f.mTarget != null) {
2926                        if (f.mTarget.mIndex < 0) {
2927                            throwException(new IllegalStateException(
2928                                    "Failure saving state: " + f
2929                                    + " has target not in fragment manager: " + f.mTarget));
2930                        }
2931                        if (fs.mSavedFragmentState == null) {
2932                            fs.mSavedFragmentState = new Bundle();
2933                        }
2934                        putFragment(fs.mSavedFragmentState,
2935                                FragmentManagerImpl.TARGET_STATE_TAG, f.mTarget);
2936                        if (f.mTargetRequestCode != 0) {
2937                            fs.mSavedFragmentState.putInt(
2938                                    FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG,
2939                                    f.mTargetRequestCode);
2940                        }
2941                    }
2942
2943                } else {
2944                    fs.mSavedFragmentState = f.mSavedFragmentState;
2945                }
2946
2947                if (DEBUG) Log.v(TAG, "Saved state of " + f + ": "
2948                        + fs.mSavedFragmentState);
2949            }
2950        }
2951
2952        if (!haveFragments) {
2953            if (DEBUG) Log.v(TAG, "saveAllState: no fragments!");
2954            return null;
2955        }
2956
2957        int[] added = null;
2958        BackStackState[] backStack = null;
2959
2960        // Build list of currently added fragments.
2961        N = mAdded.size();
2962        if (N > 0) {
2963            added = new int[N];
2964            for (int i = 0; i < N; i++) {
2965                added[i] = mAdded.get(i).mIndex;
2966                if (added[i] < 0) {
2967                    throwException(new IllegalStateException(
2968                            "Failure saving state: active " + mAdded.get(i)
2969                            + " has cleared index: " + added[i]));
2970                }
2971                if (DEBUG) {
2972                    Log.v(TAG, "saveAllState: adding fragment #" + i
2973                            + ": " + mAdded.get(i));
2974                }
2975            }
2976        }
2977
2978        // Now save back stack.
2979        if (mBackStack != null) {
2980            N = mBackStack.size();
2981            if (N > 0) {
2982                backStack = new BackStackState[N];
2983                for (int i=0; i<N; i++) {
2984                    backStack[i] = new BackStackState(mBackStack.get(i));
2985                    if (DEBUG) Log.v(TAG, "saveAllState: adding back stack #" + i
2986                            + ": " + mBackStack.get(i));
2987                }
2988            }
2989        }
2990
2991        FragmentManagerState fms = new FragmentManagerState();
2992        fms.mActive = active;
2993        fms.mAdded = added;
2994        fms.mBackStack = backStack;
2995        if (mPrimaryNav != null) {
2996            fms.mPrimaryNavActiveIndex = mPrimaryNav.mIndex;
2997        }
2998        fms.mNextFragmentIndex = mNextFragmentIndex;
2999        saveNonConfig();
3000        return fms;
3001    }
3002
3003    void restoreAllState(Parcelable state, FragmentManagerNonConfig nonConfig) {
3004        // If there is no saved state at all, then there can not be
3005        // any nonConfig fragments either, so that is that.
3006        if (state == null) return;
3007        FragmentManagerState fms = (FragmentManagerState)state;
3008        if (fms.mActive == null) return;
3009
3010        List<FragmentManagerNonConfig> childNonConfigs = null;
3011
3012        // First re-attach any non-config instances we are retaining back
3013        // to their saved state, so we don't try to instantiate them again.
3014        if (nonConfig != null) {
3015            List<Fragment> nonConfigFragments = nonConfig.getFragments();
3016            childNonConfigs = nonConfig.getChildNonConfigs();
3017            final int count = nonConfigFragments != null ? nonConfigFragments.size() : 0;
3018            for (int i = 0; i < count; i++) {
3019                Fragment f = nonConfigFragments.get(i);
3020                if (DEBUG) Log.v(TAG, "restoreAllState: re-attaching retained " + f);
3021                int index = 0; // index into fms.mActive
3022                while (index < fms.mActive.length && fms.mActive[index].mIndex != f.mIndex) {
3023                    index++;
3024                }
3025                if (index == fms.mActive.length) {
3026                    throwException(new IllegalStateException("Could not find active fragment "
3027                            + "with index " + f.mIndex));
3028                }
3029                FragmentState fs = fms.mActive[index];
3030                fs.mInstance = f;
3031                f.mSavedViewState = null;
3032                f.mBackStackNesting = 0;
3033                f.mInLayout = false;
3034                f.mAdded = false;
3035                f.mTarget = null;
3036                if (fs.mSavedFragmentState != null) {
3037                    fs.mSavedFragmentState.setClassLoader(mHost.getContext().getClassLoader());
3038                    f.mSavedViewState = fs.mSavedFragmentState.getSparseParcelableArray(
3039                            FragmentManagerImpl.VIEW_STATE_TAG);
3040                    f.mSavedFragmentState = fs.mSavedFragmentState;
3041                }
3042            }
3043        }
3044
3045        // Build the full list of active fragments, instantiating them from
3046        // their saved state.
3047        mActive = new SparseArray<>(fms.mActive.length);
3048        for (int i=0; i<fms.mActive.length; i++) {
3049            FragmentState fs = fms.mActive[i];
3050            if (fs != null) {
3051                FragmentManagerNonConfig childNonConfig = null;
3052                if (childNonConfigs != null && i < childNonConfigs.size()) {
3053                    childNonConfig = childNonConfigs.get(i);
3054                }
3055                Fragment f = fs.instantiate(mHost, mContainer, mParent, childNonConfig);
3056                if (DEBUG) Log.v(TAG, "restoreAllState: active #" + i + ": " + f);
3057                mActive.put(f.mIndex, f);
3058                // Now that the fragment is instantiated (or came from being
3059                // retained above), clear mInstance in case we end up re-restoring
3060                // from this FragmentState again.
3061                fs.mInstance = null;
3062            }
3063        }
3064
3065        // Update the target of all retained fragments.
3066        if (nonConfig != null) {
3067            List<Fragment> nonConfigFragments = nonConfig.getFragments();
3068            final int count = nonConfigFragments != null ? nonConfigFragments.size() : 0;
3069            for (int i = 0; i < count; i++) {
3070                Fragment f = nonConfigFragments.get(i);
3071                if (f.mTargetIndex >= 0) {
3072                    f.mTarget = mActive.get(f.mTargetIndex);
3073                    if (f.mTarget == null) {
3074                        Log.w(TAG, "Re-attaching retained fragment " + f
3075                                + " target no longer exists: " + f.mTargetIndex);
3076                    }
3077                }
3078            }
3079        }
3080
3081        // Build the list of currently added fragments.
3082        mAdded.clear();
3083        if (fms.mAdded != null) {
3084            for (int i=0; i<fms.mAdded.length; i++) {
3085                Fragment f = mActive.get(fms.mAdded[i]);
3086                if (f == null) {
3087                    throwException(new IllegalStateException(
3088                            "No instantiated fragment for index #" + fms.mAdded[i]));
3089                }
3090                f.mAdded = true;
3091                if (DEBUG) Log.v(TAG, "restoreAllState: added #" + i + ": " + f);
3092                if (mAdded.contains(f)) {
3093                    throw new IllegalStateException("Already added!");
3094                }
3095                synchronized (mAdded) {
3096                    mAdded.add(f);
3097                }
3098            }
3099        }
3100
3101        // Build the back stack.
3102        if (fms.mBackStack != null) {
3103            mBackStack = new ArrayList<BackStackRecord>(fms.mBackStack.length);
3104            for (int i=0; i<fms.mBackStack.length; i++) {
3105                BackStackRecord bse = fms.mBackStack[i].instantiate(this);
3106                if (DEBUG) {
3107                    Log.v(TAG, "restoreAllState: back stack #" + i
3108                        + " (index " + bse.mIndex + "): " + bse);
3109                    LogWriter logw = new LogWriter(TAG);
3110                    PrintWriter pw = new PrintWriter(logw);
3111                    bse.dump("  ", pw, false);
3112                    pw.close();
3113                }
3114                mBackStack.add(bse);
3115                if (bse.mIndex >= 0) {
3116                    setBackStackIndex(bse.mIndex, bse);
3117                }
3118            }
3119        } else {
3120            mBackStack = null;
3121        }
3122
3123        if (fms.mPrimaryNavActiveIndex >= 0) {
3124            mPrimaryNav = mActive.get(fms.mPrimaryNavActiveIndex);
3125        }
3126        this.mNextFragmentIndex = fms.mNextFragmentIndex;
3127    }
3128
3129    /**
3130     * To prevent list modification errors, mActive sets values to null instead of
3131     * removing them when the Fragment becomes inactive. This cleans up the list at the
3132     * end of executing the transactions.
3133     */
3134    private void burpActive() {
3135        if (mActive != null) {
3136            for (int i = mActive.size() - 1; i >= 0; i--) {
3137                if (mActive.valueAt(i) == null) {
3138                    mActive.delete(mActive.keyAt(i));
3139                }
3140            }
3141        }
3142    }
3143
3144    public void attachController(FragmentHostCallback host,
3145            FragmentContainer container, Fragment parent) {
3146        if (mHost != null) throw new IllegalStateException("Already attached");
3147        mHost = host;
3148        mContainer = container;
3149        mParent = parent;
3150    }
3151
3152    public void noteStateNotSaved() {
3153        mSavedNonConfig = null;
3154        mStateSaved = false;
3155        final int addedCount = mAdded.size();
3156        for (int i = 0; i < addedCount; i++) {
3157            Fragment fragment = mAdded.get(i);
3158            if (fragment != null) {
3159                fragment.noteStateNotSaved();
3160            }
3161        }
3162    }
3163
3164    public void dispatchCreate() {
3165        mStateSaved = false;
3166        dispatchStateChange(Fragment.CREATED);
3167    }
3168
3169    public void dispatchActivityCreated() {
3170        mStateSaved = false;
3171        dispatchStateChange(Fragment.ACTIVITY_CREATED);
3172    }
3173
3174    public void dispatchStart() {
3175        mStateSaved = false;
3176        dispatchStateChange(Fragment.STARTED);
3177    }
3178
3179    public void dispatchResume() {
3180        mStateSaved = false;
3181        dispatchStateChange(Fragment.RESUMED);
3182    }
3183
3184    public void dispatchPause() {
3185        dispatchStateChange(Fragment.STARTED);
3186    }
3187
3188    public void dispatchStop() {
3189        // See saveAllState() for the explanation of this.  We do this for
3190        // all platform versions, to keep our behavior more consistent between
3191        // them.
3192        mStateSaved = true;
3193
3194        dispatchStateChange(Fragment.STOPPED);
3195    }
3196
3197    public void dispatchReallyStop() {
3198        dispatchStateChange(Fragment.ACTIVITY_CREATED);
3199    }
3200
3201    public void dispatchDestroyView() {
3202        dispatchStateChange(Fragment.CREATED);
3203    }
3204
3205    public void dispatchDestroy() {
3206        mDestroyed = true;
3207        execPendingActions();
3208        dispatchStateChange(Fragment.INITIALIZING);
3209        mHost = null;
3210        mContainer = null;
3211        mParent = null;
3212    }
3213
3214    private void dispatchStateChange(int nextState) {
3215        try {
3216            mExecutingActions = true;
3217            moveToState(nextState, false);
3218        } finally {
3219            mExecutingActions = false;
3220        }
3221        execPendingActions();
3222    }
3223
3224    public void dispatchMultiWindowModeChanged(boolean isInMultiWindowMode) {
3225        for (int i = mAdded.size() - 1; i >= 0; --i) {
3226            final android.support.v4.app.Fragment f = mAdded.get(i);
3227            if (f != null) {
3228                f.performMultiWindowModeChanged(isInMultiWindowMode);
3229            }
3230        }
3231    }
3232
3233    public void dispatchPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
3234        for (int i = mAdded.size() - 1; i >= 0; --i) {
3235            final android.support.v4.app.Fragment f = mAdded.get(i);
3236            if (f != null) {
3237                f.performPictureInPictureModeChanged(isInPictureInPictureMode);
3238            }
3239        }
3240    }
3241
3242    public void dispatchConfigurationChanged(Configuration newConfig) {
3243        for (int i = 0; i < mAdded.size(); i++) {
3244            Fragment f = mAdded.get(i);
3245            if (f != null) {
3246                f.performConfigurationChanged(newConfig);
3247            }
3248        }
3249    }
3250
3251    public void dispatchLowMemory() {
3252        for (int i = 0; i < mAdded.size(); i++) {
3253            Fragment f = mAdded.get(i);
3254            if (f != null) {
3255                f.performLowMemory();
3256            }
3257        }
3258    }
3259
3260    public boolean dispatchCreateOptionsMenu(Menu menu, MenuInflater inflater) {
3261        if (mCurState < Fragment.CREATED) {
3262            return false;
3263        }
3264        boolean show = false;
3265        ArrayList<Fragment> newMenus = null;
3266        for (int i = 0; i < mAdded.size(); i++) {
3267            Fragment f = mAdded.get(i);
3268            if (f != null) {
3269                if (f.performCreateOptionsMenu(menu, inflater)) {
3270                    show = true;
3271                    if (newMenus == null) {
3272                        newMenus = new ArrayList<Fragment>();
3273                    }
3274                    newMenus.add(f);
3275                }
3276            }
3277        }
3278
3279        if (mCreatedMenus != null) {
3280            for (int i=0; i<mCreatedMenus.size(); i++) {
3281                Fragment f = mCreatedMenus.get(i);
3282                if (newMenus == null || !newMenus.contains(f)) {
3283                    f.onDestroyOptionsMenu();
3284                }
3285            }
3286        }
3287
3288        mCreatedMenus = newMenus;
3289
3290        return show;
3291    }
3292
3293    public boolean dispatchPrepareOptionsMenu(Menu menu) {
3294        if (mCurState < Fragment.CREATED) {
3295            return false;
3296        }
3297        boolean show = false;
3298        for (int i = 0; i < mAdded.size(); i++) {
3299            Fragment f = mAdded.get(i);
3300            if (f != null) {
3301                if (f.performPrepareOptionsMenu(menu)) {
3302                    show = true;
3303                }
3304            }
3305        }
3306        return show;
3307    }
3308
3309    public boolean dispatchOptionsItemSelected(MenuItem item) {
3310        if (mCurState < Fragment.CREATED) {
3311            return false;
3312        }
3313        for (int i = 0; i < mAdded.size(); i++) {
3314            Fragment f = mAdded.get(i);
3315            if (f != null) {
3316                if (f.performOptionsItemSelected(item)) {
3317                    return true;
3318                }
3319            }
3320        }
3321        return false;
3322    }
3323
3324    public boolean dispatchContextItemSelected(MenuItem item) {
3325        if (mCurState < Fragment.CREATED) {
3326            return false;
3327        }
3328        for (int i = 0; i < mAdded.size(); i++) {
3329            Fragment f = mAdded.get(i);
3330            if (f != null) {
3331                if (f.performContextItemSelected(item)) {
3332                    return true;
3333                }
3334            }
3335        }
3336        return false;
3337    }
3338
3339    public void dispatchOptionsMenuClosed(Menu menu) {
3340        if (mCurState < Fragment.CREATED) {
3341            return;
3342        }
3343        for (int i = 0; i < mAdded.size(); i++) {
3344            Fragment f = mAdded.get(i);
3345            if (f != null) {
3346                f.performOptionsMenuClosed(menu);
3347            }
3348        }
3349    }
3350
3351    @SuppressWarnings("ReferenceEquality")
3352    public void setPrimaryNavigationFragment(Fragment f) {
3353        if (f != null && (mActive.get(f.mIndex) != f
3354            || (f.mHost != null && f.getFragmentManager() != this))) {
3355            throw new IllegalArgumentException("Fragment " + f
3356                    + " is not an active fragment of FragmentManager " + this);
3357        }
3358        mPrimaryNav = f;
3359    }
3360
3361    @Override
3362    public Fragment getPrimaryNavigationFragment() {
3363        return mPrimaryNav;
3364    }
3365
3366    @Override
3367    public void registerFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb,
3368            boolean recursive) {
3369        mLifecycleCallbacks.add(new Pair<>(cb, recursive));
3370    }
3371
3372    @Override
3373    public void unregisterFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb) {
3374        synchronized (mLifecycleCallbacks) {
3375            for (int i = 0, N = mLifecycleCallbacks.size(); i < N; i++) {
3376                if (mLifecycleCallbacks.get(i).first == cb) {
3377                    mLifecycleCallbacks.remove(i);
3378                    break;
3379                }
3380            }
3381        }
3382    }
3383
3384    void dispatchOnFragmentPreAttached(Fragment f, Context context, boolean onlyRecursive) {
3385        if (mParent != null) {
3386            FragmentManager parentManager = mParent.getFragmentManager();
3387            if (parentManager instanceof FragmentManagerImpl) {
3388                ((FragmentManagerImpl) parentManager)
3389                        .dispatchOnFragmentPreAttached(f, context, true);
3390            }
3391        }
3392        for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
3393            if (!onlyRecursive || p.second) {
3394                p.first.onFragmentPreAttached(this, f, context);
3395            }
3396        }
3397    }
3398
3399    void dispatchOnFragmentAttached(Fragment f, Context context, boolean onlyRecursive) {
3400        if (mParent != null) {
3401            FragmentManager parentManager = mParent.getFragmentManager();
3402            if (parentManager instanceof FragmentManagerImpl) {
3403                ((FragmentManagerImpl) parentManager)
3404                        .dispatchOnFragmentAttached(f, context, true);
3405            }
3406        }
3407        for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
3408            if (!onlyRecursive || p.second) {
3409                p.first.onFragmentAttached(this, f, context);
3410            }
3411        }
3412    }
3413
3414    void dispatchOnFragmentPreCreated(Fragment f, Bundle savedInstanceState,
3415            boolean onlyRecursive) {
3416        if (mParent != null) {
3417            FragmentManager parentManager = mParent.getFragmentManager();
3418            if (parentManager instanceof FragmentManagerImpl) {
3419                ((FragmentManagerImpl) parentManager)
3420                        .dispatchOnFragmentPreCreated(f, savedInstanceState, true);
3421            }
3422        }
3423        for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
3424            if (!onlyRecursive || p.second) {
3425                p.first.onFragmentPreCreated(this, f, savedInstanceState);
3426            }
3427        }
3428    }
3429
3430    void dispatchOnFragmentCreated(Fragment f, Bundle savedInstanceState, boolean onlyRecursive) {
3431        if (mParent != null) {
3432            FragmentManager parentManager = mParent.getFragmentManager();
3433            if (parentManager instanceof FragmentManagerImpl) {
3434                ((FragmentManagerImpl) parentManager)
3435                        .dispatchOnFragmentCreated(f, savedInstanceState, true);
3436            }
3437        }
3438        for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
3439            if (!onlyRecursive || p.second) {
3440                p.first.onFragmentCreated(this, f, savedInstanceState);
3441            }
3442        }
3443    }
3444
3445    void dispatchOnFragmentActivityCreated(Fragment f, Bundle savedInstanceState,
3446            boolean onlyRecursive) {
3447        if (mParent != null) {
3448            FragmentManager parentManager = mParent.getFragmentManager();
3449            if (parentManager instanceof FragmentManagerImpl) {
3450                ((FragmentManagerImpl) parentManager)
3451                        .dispatchOnFragmentActivityCreated(f, savedInstanceState, true);
3452            }
3453        }
3454        for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
3455            if (!onlyRecursive || p.second) {
3456                p.first.onFragmentActivityCreated(this, f, savedInstanceState);
3457            }
3458        }
3459    }
3460
3461    void dispatchOnFragmentViewCreated(Fragment f, View v, Bundle savedInstanceState,
3462            boolean onlyRecursive) {
3463        if (mParent != null) {
3464            FragmentManager parentManager = mParent.getFragmentManager();
3465            if (parentManager instanceof FragmentManagerImpl) {
3466                ((FragmentManagerImpl) parentManager)
3467                        .dispatchOnFragmentViewCreated(f, v, savedInstanceState, true);
3468            }
3469        }
3470        for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
3471            if (!onlyRecursive || p.second) {
3472                p.first.onFragmentViewCreated(this, f, v, savedInstanceState);
3473            }
3474        }
3475    }
3476
3477    void dispatchOnFragmentStarted(Fragment f, boolean onlyRecursive) {
3478        if (mParent != null) {
3479            FragmentManager parentManager = mParent.getFragmentManager();
3480            if (parentManager instanceof FragmentManagerImpl) {
3481                ((FragmentManagerImpl) parentManager)
3482                        .dispatchOnFragmentStarted(f, true);
3483            }
3484        }
3485        for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
3486            if (!onlyRecursive || p.second) {
3487                p.first.onFragmentStarted(this, f);
3488            }
3489        }
3490    }
3491
3492    void dispatchOnFragmentResumed(Fragment f, boolean onlyRecursive) {
3493        if (mParent != null) {
3494            FragmentManager parentManager = mParent.getFragmentManager();
3495            if (parentManager instanceof FragmentManagerImpl) {
3496                ((FragmentManagerImpl) parentManager)
3497                        .dispatchOnFragmentResumed(f, true);
3498            }
3499        }
3500        for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
3501            if (!onlyRecursive || p.second) {
3502                p.first.onFragmentResumed(this, f);
3503            }
3504        }
3505    }
3506
3507    void dispatchOnFragmentPaused(Fragment f, boolean onlyRecursive) {
3508        if (mParent != null) {
3509            FragmentManager parentManager = mParent.getFragmentManager();
3510            if (parentManager instanceof FragmentManagerImpl) {
3511                ((FragmentManagerImpl) parentManager)
3512                        .dispatchOnFragmentPaused(f, true);
3513            }
3514        }
3515        for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
3516            if (!onlyRecursive || p.second) {
3517                p.first.onFragmentPaused(this, f);
3518            }
3519        }
3520    }
3521
3522    void dispatchOnFragmentStopped(Fragment f, boolean onlyRecursive) {
3523        if (mParent != null) {
3524            FragmentManager parentManager = mParent.getFragmentManager();
3525            if (parentManager instanceof FragmentManagerImpl) {
3526                ((FragmentManagerImpl) parentManager)
3527                        .dispatchOnFragmentStopped(f, true);
3528            }
3529        }
3530        for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
3531            if (!onlyRecursive || p.second) {
3532                p.first.onFragmentStopped(this, f);
3533            }
3534        }
3535    }
3536
3537    void dispatchOnFragmentSaveInstanceState(Fragment f, Bundle outState, boolean onlyRecursive) {
3538        if (mParent != null) {
3539            FragmentManager parentManager = mParent.getFragmentManager();
3540            if (parentManager instanceof FragmentManagerImpl) {
3541                ((FragmentManagerImpl) parentManager)
3542                        .dispatchOnFragmentSaveInstanceState(f, outState, true);
3543            }
3544        }
3545        for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
3546            if (!onlyRecursive || p.second) {
3547                p.first.onFragmentSaveInstanceState(this, f, outState);
3548            }
3549        }
3550    }
3551
3552    void dispatchOnFragmentViewDestroyed(Fragment f, boolean onlyRecursive) {
3553        if (mParent != null) {
3554            FragmentManager parentManager = mParent.getFragmentManager();
3555            if (parentManager instanceof FragmentManagerImpl) {
3556                ((FragmentManagerImpl) parentManager)
3557                        .dispatchOnFragmentViewDestroyed(f, true);
3558            }
3559        }
3560        for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
3561            if (!onlyRecursive || p.second) {
3562                p.first.onFragmentViewDestroyed(this, f);
3563            }
3564        }
3565    }
3566
3567    void dispatchOnFragmentDestroyed(Fragment f, boolean onlyRecursive) {
3568        if (mParent != null) {
3569            FragmentManager parentManager = mParent.getFragmentManager();
3570            if (parentManager instanceof FragmentManagerImpl) {
3571                ((FragmentManagerImpl) parentManager)
3572                        .dispatchOnFragmentDestroyed(f, true);
3573            }
3574        }
3575        for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
3576            if (!onlyRecursive || p.second) {
3577                p.first.onFragmentDestroyed(this, f);
3578            }
3579        }
3580    }
3581
3582    void dispatchOnFragmentDetached(Fragment f, boolean onlyRecursive) {
3583        if (mParent != null) {
3584            FragmentManager parentManager = mParent.getFragmentManager();
3585            if (parentManager instanceof FragmentManagerImpl) {
3586                ((FragmentManagerImpl) parentManager)
3587                        .dispatchOnFragmentDetached(f, true);
3588            }
3589        }
3590        for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
3591            if (!onlyRecursive || p.second) {
3592                p.first.onFragmentDetached(this, f);
3593            }
3594        }
3595    }
3596
3597    public static int reverseTransit(int transit) {
3598        int rev = 0;
3599        switch (transit) {
3600            case FragmentTransaction.TRANSIT_FRAGMENT_OPEN:
3601                rev = FragmentTransaction.TRANSIT_FRAGMENT_CLOSE;
3602                break;
3603            case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE:
3604                rev = FragmentTransaction.TRANSIT_FRAGMENT_OPEN;
3605                break;
3606            case FragmentTransaction.TRANSIT_FRAGMENT_FADE:
3607                rev = FragmentTransaction.TRANSIT_FRAGMENT_FADE;
3608                break;
3609        }
3610        return rev;
3611
3612    }
3613
3614    public static final int ANIM_STYLE_OPEN_ENTER = 1;
3615    public static final int ANIM_STYLE_OPEN_EXIT = 2;
3616    public static final int ANIM_STYLE_CLOSE_ENTER = 3;
3617    public static final int ANIM_STYLE_CLOSE_EXIT = 4;
3618    public static final int ANIM_STYLE_FADE_ENTER = 5;
3619    public static final int ANIM_STYLE_FADE_EXIT = 6;
3620
3621    public static int transitToStyleIndex(int transit, boolean enter) {
3622        int animAttr = -1;
3623        switch (transit) {
3624            case FragmentTransaction.TRANSIT_FRAGMENT_OPEN:
3625                animAttr = enter ? ANIM_STYLE_OPEN_ENTER : ANIM_STYLE_OPEN_EXIT;
3626                break;
3627            case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE:
3628                animAttr = enter ? ANIM_STYLE_CLOSE_ENTER : ANIM_STYLE_CLOSE_EXIT;
3629                break;
3630            case FragmentTransaction.TRANSIT_FRAGMENT_FADE:
3631                animAttr = enter ? ANIM_STYLE_FADE_ENTER : ANIM_STYLE_FADE_EXIT;
3632                break;
3633        }
3634        return animAttr;
3635    }
3636
3637    @Override
3638    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
3639        if (!"fragment".equals(name)) {
3640            return null;
3641        }
3642
3643        String fname = attrs.getAttributeValue(null, "class");
3644        TypedArray a =  context.obtainStyledAttributes(attrs, FragmentTag.Fragment);
3645        if (fname == null) {
3646            fname = a.getString(FragmentTag.Fragment_name);
3647        }
3648        int id = a.getResourceId(FragmentTag.Fragment_id, View.NO_ID);
3649        String tag = a.getString(FragmentTag.Fragment_tag);
3650        a.recycle();
3651
3652        if (!Fragment.isSupportFragmentClass(mHost.getContext(), fname)) {
3653            // Invalid support lib fragment; let the device's framework handle it.
3654            // This will allow android.app.Fragments to do the right thing.
3655            return null;
3656        }
3657
3658        int containerId = parent != null ? parent.getId() : 0;
3659        if (containerId == View.NO_ID && id == View.NO_ID && tag == null) {
3660            throw new IllegalArgumentException(attrs.getPositionDescription()
3661                    + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname);
3662        }
3663
3664        // If we restored from a previous state, we may already have
3665        // instantiated this fragment from the state and should use
3666        // that instance instead of making a new one.
3667        Fragment fragment = id != View.NO_ID ? findFragmentById(id) : null;
3668        if (fragment == null && tag != null) {
3669            fragment = findFragmentByTag(tag);
3670        }
3671        if (fragment == null && containerId != View.NO_ID) {
3672            fragment = findFragmentById(containerId);
3673        }
3674
3675        if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x"
3676                + Integer.toHexString(id) + " fname=" + fname
3677                + " existing=" + fragment);
3678        if (fragment == null) {
3679            fragment = mContainer.instantiate(context, fname, null);
3680            fragment.mFromLayout = true;
3681            fragment.mFragmentId = id != 0 ? id : containerId;
3682            fragment.mContainerId = containerId;
3683            fragment.mTag = tag;
3684            fragment.mInLayout = true;
3685            fragment.mFragmentManager = this;
3686            fragment.mHost = mHost;
3687            fragment.onInflate(mHost.getContext(), attrs, fragment.mSavedFragmentState);
3688            addFragment(fragment, true);
3689
3690        } else if (fragment.mInLayout) {
3691            // A fragment already exists and it is not one we restored from
3692            // previous state.
3693            throw new IllegalArgumentException(attrs.getPositionDescription()
3694                    + ": Duplicate id 0x" + Integer.toHexString(id)
3695                    + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
3696                    + " with another fragment for " + fname);
3697        } else {
3698            // This fragment was retained from a previous instance; get it
3699            // going now.
3700            fragment.mInLayout = true;
3701            fragment.mHost = mHost;
3702            // If this fragment is newly instantiated (either right now, or
3703            // from last saved state), then give it the attributes to
3704            // initialize itself.
3705            if (!fragment.mRetaining) {
3706                fragment.onInflate(mHost.getContext(), attrs, fragment.mSavedFragmentState);
3707            }
3708        }
3709
3710        // If we haven't finished entering the CREATED state ourselves yet,
3711        // push the inflated child fragment along. This will ensureInflatedFragmentView
3712        // at the right phase of the lifecycle so that we will have mView populated
3713        // for compliant fragments below.
3714        if (mCurState < Fragment.CREATED && fragment.mFromLayout) {
3715            moveToState(fragment, Fragment.CREATED, 0, 0, false);
3716        } else {
3717            moveToState(fragment);
3718        }
3719
3720        if (fragment.mView == null) {
3721            throw new IllegalStateException("Fragment " + fname
3722                    + " did not create a view.");
3723        }
3724        if (id != 0) {
3725            fragment.mView.setId(id);
3726        }
3727        if (fragment.mView.getTag() == null) {
3728            fragment.mView.setTag(tag);
3729        }
3730        return fragment.mView;
3731    }
3732
3733    @Override
3734    public View onCreateView(String name, Context context, AttributeSet attrs) {
3735        return onCreateView(null, name, context, attrs);
3736    }
3737
3738    LayoutInflater.Factory2 getLayoutInflaterFactory() {
3739        return this;
3740    }
3741
3742    static class FragmentTag {
3743        public static final int[] Fragment = {
3744                0x01010003, 0x010100d0, 0x010100d1
3745        };
3746        public static final int Fragment_id = 1;
3747        public static final int Fragment_name = 0;
3748        public static final int Fragment_tag = 2;
3749    }
3750
3751    /**
3752     * An add or pop transaction to be scheduled for the UI thread.
3753     */
3754    interface OpGenerator {
3755        /**
3756         * Generate transactions to add to {@code records} and whether or not the transaction is
3757         * an add or pop to {@code isRecordPop}.
3758         *
3759         * records and isRecordPop must be added equally so that each transaction in records
3760         * matches the boolean for whether or not it is a pop in isRecordPop.
3761         *
3762         * @param records A list to add transactions to.
3763         * @param isRecordPop A list to add whether or not the transactions added to records is
3764         *                    a pop transaction.
3765         * @return true if something was added or false otherwise.
3766         */
3767        boolean generateOps(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop);
3768    }
3769
3770    /**
3771     * A pop operation OpGenerator. This will be run on the UI thread and will generate the
3772     * transactions that will be popped if anything can be popped.
3773     */
3774    private class PopBackStackState implements OpGenerator {
3775        final String mName;
3776        final int mId;
3777        final int mFlags;
3778
3779        PopBackStackState(String name, int id, int flags) {
3780            mName = name;
3781            mId = id;
3782            mFlags = flags;
3783        }
3784
3785        @Override
3786        public boolean generateOps(ArrayList<BackStackRecord> records,
3787                ArrayList<Boolean> isRecordPop) {
3788            if (mPrimaryNav != null // We have a primary nav fragment
3789                    && mId < 0 // No valid id (since they're local)
3790                    && mName == null) { // no name to pop to (since they're local)
3791                final FragmentManager childManager = mPrimaryNav.peekChildFragmentManager();
3792                if (childManager != null && childManager.popBackStackImmediate()) {
3793                    // We didn't add any operations for this FragmentManager even though
3794                    // a child did do work.
3795                    return false;
3796                }
3797            }
3798            return popBackStackState(records, isRecordPop, mName, mId, mFlags);
3799        }
3800    }
3801
3802    /**
3803     * A listener for a postponed transaction. This waits until
3804     * {@link Fragment#startPostponedEnterTransition()} is called or a transaction is started
3805     * that interacts with this one, based on interactions with the fragment container.
3806     */
3807    static class StartEnterTransitionListener
3808            implements Fragment.OnStartEnterTransitionListener {
3809        private final boolean mIsBack;
3810        private final BackStackRecord mRecord;
3811        private int mNumPostponed;
3812
3813        StartEnterTransitionListener(BackStackRecord record, boolean isBack) {
3814            mIsBack = isBack;
3815            mRecord = record;
3816        }
3817
3818        /**
3819         * Called from {@link Fragment#startPostponedEnterTransition()}, this decreases the
3820         * number of Fragments that are postponed. This may cause the transaction to schedule
3821         * to finish running and run transitions and animations.
3822         */
3823        @Override
3824        public void onStartEnterTransition() {
3825            mNumPostponed--;
3826            if (mNumPostponed != 0) {
3827                return;
3828            }
3829            mRecord.mManager.scheduleCommit();
3830        }
3831
3832        /**
3833         * Called from {@link Fragment#
3834         * setOnStartEnterTransitionListener(Fragment.OnStartEnterTransitionListener)}, this
3835         * increases the number of fragments that are postponed as part of this transaction.
3836         */
3837        @Override
3838        public void startListening() {
3839            mNumPostponed++;
3840        }
3841
3842        /**
3843         * @return true if there are no more postponed fragments as part of the transaction.
3844         */
3845        public boolean isReady() {
3846            return mNumPostponed == 0;
3847        }
3848
3849        /**
3850         * Completes the transaction and start the animations and transitions. This may skip
3851         * the transitions if this is called before all fragments have called
3852         * {@link Fragment#startPostponedEnterTransition()}.
3853         */
3854        public void completeTransaction() {
3855            final boolean canceled;
3856            canceled = mNumPostponed > 0;
3857            FragmentManagerImpl manager = mRecord.mManager;
3858            final int numAdded = manager.mAdded.size();
3859            for (int i = 0; i < numAdded; i++) {
3860                final Fragment fragment = manager.mAdded.get(i);
3861                fragment.setOnStartEnterTransitionListener(null);
3862                if (canceled && fragment.isPostponed()) {
3863                    fragment.startPostponedEnterTransition();
3864                }
3865            }
3866            mRecord.mManager.completeExecute(mRecord, mIsBack, !canceled, true);
3867        }
3868
3869        /**
3870         * Cancels this transaction instead of completing it. That means that the state isn't
3871         * changed, so the pop results in no change to the state.
3872         */
3873        public void cancelTransaction() {
3874            mRecord.mManager.completeExecute(mRecord, mIsBack, false, false);
3875        }
3876    }
3877
3878    /**
3879     * Contains either an animator or animation. One of these should be null.
3880     */
3881    private static class AnimationOrAnimator {
3882        public final Animation animation;
3883        public final Animator animator;
3884
3885        private AnimationOrAnimator(Animation animation) {
3886            this.animation = animation;
3887            this.animator = null;
3888            if (animation == null) {
3889                throw new IllegalStateException("Animation cannot be null");
3890            }
3891        }
3892
3893        private AnimationOrAnimator(Animator animator) {
3894            this.animation = null;
3895            this.animator = animator;
3896            if (animator == null) {
3897                throw new IllegalStateException("Animator cannot be null");
3898            }
3899        }
3900    }
3901
3902    /**
3903     * Wrap an AnimationListener that can be null. This allows us to chain animation listeners.
3904     */
3905    private static class AnimationListenerWrapper implements AnimationListener {
3906        private final AnimationListener mWrapped;
3907
3908        private AnimationListenerWrapper(AnimationListener wrapped) {
3909            mWrapped = wrapped;
3910        }
3911
3912        @CallSuper
3913        @Override
3914        public void onAnimationStart(Animation animation) {
3915            if (mWrapped != null) {
3916                mWrapped.onAnimationStart(animation);
3917            }
3918        }
3919
3920        @CallSuper
3921        @Override
3922        public void onAnimationEnd(Animation animation) {
3923            if (mWrapped != null) {
3924                mWrapped.onAnimationEnd(animation);
3925            }
3926        }
3927
3928        @CallSuper
3929        @Override
3930        public void onAnimationRepeat(Animation animation) {
3931            if (mWrapped != null) {
3932                mWrapped.onAnimationRepeat(animation);
3933            }
3934        }
3935    }
3936
3937    /**
3938     * Reset the layer type to LAYER_TYPE_NONE at the end of an animation.
3939     */
3940    private static class AnimateOnHWLayerIfNeededListener extends AnimationListenerWrapper  {
3941        View mView;
3942
3943        AnimateOnHWLayerIfNeededListener(final View v, AnimationListener listener) {
3944            super(listener);
3945            mView = v;
3946        }
3947
3948        @Override
3949        @CallSuper
3950        public void onAnimationEnd(Animation animation) {
3951            // If we're attached to a window, assume we're in the normal performTraversals
3952            // drawing path for Animations running. It's not safe to change the layer type
3953            // during drawing, so post it to the View to run later. If we're not attached
3954            // or we're running on N and above, post it to the view. If we're not on N and
3955            // not attached, do it right now since existing platform versions don't run the
3956            // hwui renderer for detached views off the UI thread making changing layer type
3957            // safe, but posting may not be.
3958            // Prior to N posting to a detached view from a non-Looper thread could cause
3959            // leaks, since the thread-local run queue on a non-Looper thread would never
3960            // be flushed.
3961            if (ViewCompat.isAttachedToWindow(mView) || Build.VERSION.SDK_INT >= 24) {
3962                mView.post(new Runnable() {
3963                    @Override
3964                    public void run() {
3965                        mView.setLayerType(View.LAYER_TYPE_NONE, null);
3966                    }
3967                });
3968            } else {
3969                mView.setLayerType(View.LAYER_TYPE_NONE, null);
3970            }
3971            super.onAnimationEnd(animation);
3972        }
3973    }
3974
3975    /**
3976     * Set the layer type to LAYER_TYPE_HARDWARE while an animator is running.
3977     */
3978    private static class AnimatorOnHWLayerIfNeededListener extends AnimatorListenerAdapter  {
3979        View mView;
3980
3981        AnimatorOnHWLayerIfNeededListener(final View v) {
3982            mView = v;
3983        }
3984
3985        @Override
3986        public void onAnimationStart(Animator animation) {
3987            mView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
3988        }
3989
3990        @Override
3991        public void onAnimationEnd(Animator animation) {
3992            mView.setLayerType(View.LAYER_TYPE_NONE, null);
3993            animation.removeListener(this);
3994        }
3995    }
3996}
3997