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