FragmentManager.java revision 33644b9ba7d092d5686b4d85c0006066b78fcf2d
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
19import android.animation.Animator;
20import android.animation.AnimatorInflater;
21import android.animation.AnimatorListenerAdapter;
22import android.content.res.Configuration;
23import android.content.res.TypedArray;
24import android.os.Bundle;
25import android.os.Handler;
26import android.os.Looper;
27import android.os.Parcel;
28import android.os.Parcelable;
29import android.util.DebugUtils;
30import android.util.Log;
31import android.util.LogWriter;
32import android.util.Slog;
33import android.util.SparseArray;
34import android.view.Menu;
35import android.view.MenuInflater;
36import android.view.MenuItem;
37import android.view.View;
38import android.view.ViewGroup;
39
40import java.io.FileDescriptor;
41import java.io.PrintWriter;
42import java.util.ArrayList;
43import java.util.Arrays;
44
45/**
46 * Interface for interacting with {@link Fragment} objects inside of an
47 * {@link Activity}
48 *
49 * <div class="special reference">
50 * <h3>Developer Guides</h3>
51 * <p>For more information about using fragments, read the
52 * <a href="{@docRoot}guide/topics/fundamentals/fragments.html">Fragments</a> developer guide.</p>
53 * </div>
54 *
55 * While the FragmentManager API was introduced in
56 * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, a version of the API
57 * at is also available for use on older platforms through
58 * {@link android.support.v4.app.FragmentActivity}.  See the blog post
59 * <a href="http://android-developers.blogspot.com/2011/03/fragments-for-all.html">
60 * Fragments For All</a> for more details.
61 */
62public abstract class FragmentManager {
63    /**
64     * Representation of an entry on the fragment back stack, as created
65     * with {@link FragmentTransaction#addToBackStack(String)
66     * FragmentTransaction.addToBackStack()}.  Entries can later be
67     * retrieved with {@link FragmentManager#getBackStackEntryAt(int)
68     * FragmentManager.getBackStackEntry()}.
69     *
70     * <p>Note that you should never hold on to a BackStackEntry object;
71     * the identifier as returned by {@link #getId} is the only thing that
72     * will be persisted across activity instances.
73     */
74    public interface BackStackEntry {
75        /**
76         * Return the unique identifier for the entry.  This is the only
77         * representation of the entry that will persist across activity
78         * instances.
79         */
80        public int getId();
81
82        /**
83         * Get the name that was supplied to
84         * {@link FragmentTransaction#addToBackStack(String)
85         * FragmentTransaction.addToBackStack(String)} when creating this entry.
86         */
87        public String getName();
88
89        /**
90         * Return the full bread crumb title resource identifier for the entry,
91         * or 0 if it does not have one.
92         */
93        public int getBreadCrumbTitleRes();
94
95        /**
96         * Return the short bread crumb title resource identifier for the entry,
97         * or 0 if it does not have one.
98         */
99        public int getBreadCrumbShortTitleRes();
100
101        /**
102         * Return the full bread crumb title for the entry, or null if it
103         * does not have one.
104         */
105        public CharSequence getBreadCrumbTitle();
106
107        /**
108         * Return the short bread crumb title for the entry, or null if it
109         * does not have one.
110         */
111        public CharSequence getBreadCrumbShortTitle();
112    }
113
114    /**
115     * Interface to watch for changes to the back stack.
116     */
117    public interface OnBackStackChangedListener {
118        /**
119         * Called whenever the contents of the back stack change.
120         */
121        public void onBackStackChanged();
122    }
123
124    /**
125     * Start a series of edit operations on the Fragments associated with
126     * this FragmentManager.
127     *
128     * <p>Note: A fragment transaction can only be created/committed prior
129     * to an activity saving its state.  If you try to commit a transaction
130     * after {@link Activity#onSaveInstanceState Activity.onSaveInstanceState()}
131     * (and prior to a following {@link Activity#onStart Activity.onStart}
132     * or {@link Activity#onResume Activity.onResume()}, you will get an error.
133     * This is because the framework takes care of saving your current fragments
134     * in the state, and if changes are made after the state is saved then they
135     * will be lost.</p>
136     */
137    public abstract FragmentTransaction beginTransaction();
138
139    /** @hide -- remove once prebuilts are in. */
140    @Deprecated
141    public FragmentTransaction openTransaction() {
142        return beginTransaction();
143    }
144
145    /**
146     * After a {@link FragmentTransaction} is committed with
147     * {@link FragmentTransaction#commit FragmentTransaction.commit()}, it
148     * is scheduled to be executed asynchronously on the process's main thread.
149     * If you want to immediately executing any such pending operations, you
150     * can call this function (only from the main thread) to do so.  Note that
151     * all callbacks and other related behavior will be done from within this
152     * call, so be careful about where this is called from.
153     *
154     * @return Returns true if there were any pending transactions to be
155     * executed.
156     */
157    public abstract boolean executePendingTransactions();
158
159    /**
160     * Finds a fragment that was identified by the given id either when inflated
161     * from XML or as the container ID when added in a transaction.  This first
162     * searches through fragments that are currently added to the manager's
163     * activity; if no such fragment is found, then all fragments currently
164     * on the back stack associated with this ID are searched.
165     * @return The fragment if found or null otherwise.
166     */
167    public abstract Fragment findFragmentById(int id);
168
169    /**
170     * Finds a fragment that was identified by the given tag either when inflated
171     * from XML or as supplied when added in a transaction.  This first
172     * searches through fragments that are currently added to the manager's
173     * activity; if no such fragment is found, then all fragments currently
174     * on the back stack are searched.
175     * @return The fragment if found or null otherwise.
176     */
177    public abstract Fragment findFragmentByTag(String tag);
178
179    /**
180     * Flag for {@link #popBackStack(String, int)}
181     * and {@link #popBackStack(int, int)}: If set, and the name or ID of
182     * a back stack entry has been supplied, then all matching entries will
183     * be consumed until one that doesn't match is found or the bottom of
184     * the stack is reached.  Otherwise, all entries up to but not including that entry
185     * will be removed.
186     */
187    public static final int POP_BACK_STACK_INCLUSIVE = 1<<0;
188
189    /**
190     * Pop the top state off the back stack.  This function is asynchronous -- it
191     * enqueues the request to pop, but the action will not be performed until the
192     * application returns to its event loop.
193     */
194    public abstract void popBackStack();
195
196    /**
197     * Like {@link #popBackStack()}, but performs the operation immediately
198     * inside of the call.  This is like calling {@link #executePendingTransactions()}
199     * afterwards.
200     * @return Returns true if there was something popped, else false.
201     */
202    public abstract boolean popBackStackImmediate();
203
204    /**
205     * Pop the last fragment transition from the manager's fragment
206     * back stack.  If there is nothing to pop, false is returned.
207     * This function is asynchronous -- it enqueues the
208     * request to pop, but the action will not be performed until the application
209     * returns to its event loop.
210     *
211     * @param name If non-null, this is the name of a previous back state
212     * to look for; if found, all states up to that state will be popped.  The
213     * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether
214     * the named state itself is popped. If null, only the top state is popped.
215     * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}.
216     */
217    public abstract void popBackStack(String name, int flags);
218
219    /**
220     * Like {@link #popBackStack(String, int)}, but performs the operation immediately
221     * inside of the call.  This is like calling {@link #executePendingTransactions()}
222     * afterwards.
223     * @return Returns true if there was something popped, else false.
224     */
225    public abstract boolean popBackStackImmediate(String name, int flags);
226
227    /**
228     * Pop all back stack states up to the one with the given identifier.
229     * This function is asynchronous -- it enqueues the
230     * request to pop, but the action will not be performed until the application
231     * returns to its event loop.
232     *
233     * @param id Identifier of the stated to be popped. If no identifier exists,
234     * false is returned.
235     * The identifier is the number returned by
236     * {@link FragmentTransaction#commit() FragmentTransaction.commit()}.  The
237     * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether
238     * the named state itself is popped.
239     * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}.
240     */
241    public abstract void popBackStack(int id, int flags);
242
243    /**
244     * Like {@link #popBackStack(int, int)}, but performs the operation immediately
245     * inside of the call.  This is like calling {@link #executePendingTransactions()}
246     * afterwards.
247     * @return Returns true if there was something popped, else false.
248     */
249    public abstract boolean popBackStackImmediate(int id, int flags);
250
251    /**
252     * Return the number of entries currently in the back stack.
253     */
254    public abstract int getBackStackEntryCount();
255
256    /**
257     * Return the BackStackEntry at index <var>index</var> in the back stack;
258     * entries start index 0 being the bottom of the stack.
259     */
260    public abstract BackStackEntry getBackStackEntryAt(int index);
261
262    /**
263     * Add a new listener for changes to the fragment back stack.
264     */
265    public abstract void addOnBackStackChangedListener(OnBackStackChangedListener listener);
266
267    /**
268     * Remove a listener that was previously added with
269     * {@link #addOnBackStackChangedListener(OnBackStackChangedListener)}.
270     */
271    public abstract void removeOnBackStackChangedListener(OnBackStackChangedListener listener);
272
273    /**
274     * Put a reference to a fragment in a Bundle.  This Bundle can be
275     * persisted as saved state, and when later restoring
276     * {@link #getFragment(Bundle, String)} will return the current
277     * instance of the same fragment.
278     *
279     * @param bundle The bundle in which to put the fragment reference.
280     * @param key The name of the entry in the bundle.
281     * @param fragment The Fragment whose reference is to be stored.
282     */
283    public abstract void putFragment(Bundle bundle, String key, Fragment fragment);
284
285    /**
286     * Retrieve the current Fragment instance for a reference previously
287     * placed with {@link #putFragment(Bundle, String, Fragment)}.
288     *
289     * @param bundle The bundle from which to retrieve the fragment reference.
290     * @param key The name of the entry in the bundle.
291     * @return Returns the current Fragment instance that is associated with
292     * the given reference.
293     */
294    public abstract Fragment getFragment(Bundle bundle, String key);
295
296    /**
297     * Save the current instance state of the given Fragment.  This can be
298     * used later when creating a new instance of the Fragment and adding
299     * it to the fragment manager, to have it create itself to match the
300     * current state returned here.  Note that there are limits on how
301     * this can be used:
302     *
303     * <ul>
304     * <li>The Fragment must currently be attached to the FragmentManager.
305     * <li>A new Fragment created using this saved state must be the same class
306     * type as the Fragment it was created from.
307     * <li>The saved state can not contain dependencies on other fragments --
308     * that is it can't use {@link #putFragment(Bundle, String, Fragment)} to
309     * store a fragment reference because that reference may not be valid when
310     * this saved state is later used.  Likewise the Fragment's target and
311     * result code are not included in this state.
312     * </ul>
313     *
314     * @param f The Fragment whose state is to be saved.
315     * @return The generated state.  This will be null if there was no
316     * interesting state created by the fragment.
317     */
318    public abstract Fragment.SavedState saveFragmentInstanceState(Fragment f);
319
320    /**
321     * Print the FragmentManager's state into the given stream.
322     *
323     * @param prefix Text to print at the front of each line.
324     * @param fd The raw file descriptor that the dump is being sent to.
325     * @param writer A PrintWriter to which the dump is to be set.
326     * @param args Additional arguments to the dump request.
327     */
328    public abstract void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args);
329
330    /**
331     * Control whether the framework's internal fragment manager debugging
332     * logs are turned on.  If enabled, you will see output in logcat as
333     * the framework performs fragment operations.
334     */
335    public static void enableDebugLogging(boolean enabled) {
336        FragmentManagerImpl.DEBUG = enabled;
337    }
338
339    /**
340     * Invalidate the attached activity's options menu as necessary.
341     * This may end up being deferred until we move to the resumed state.
342     */
343    public void invalidateOptionsMenu() { }
344}
345
346final class FragmentManagerState implements Parcelable {
347    FragmentState[] mActive;
348    int[] mAdded;
349    BackStackState[] mBackStack;
350
351    public FragmentManagerState() {
352    }
353
354    public FragmentManagerState(Parcel in) {
355        mActive = in.createTypedArray(FragmentState.CREATOR);
356        mAdded = in.createIntArray();
357        mBackStack = in.createTypedArray(BackStackState.CREATOR);
358    }
359
360    public int describeContents() {
361        return 0;
362    }
363
364    public void writeToParcel(Parcel dest, int flags) {
365        dest.writeTypedArray(mActive, flags);
366        dest.writeIntArray(mAdded);
367        dest.writeTypedArray(mBackStack, flags);
368    }
369
370    public static final Parcelable.Creator<FragmentManagerState> CREATOR
371            = new Parcelable.Creator<FragmentManagerState>() {
372        public FragmentManagerState createFromParcel(Parcel in) {
373            return new FragmentManagerState(in);
374        }
375
376        public FragmentManagerState[] newArray(int size) {
377            return new FragmentManagerState[size];
378        }
379    };
380}
381
382/**
383 * Container for fragments associated with an activity.
384 */
385final class FragmentManagerImpl extends FragmentManager {
386    static boolean DEBUG = false;
387    static final String TAG = "FragmentManager";
388
389    static final String TARGET_REQUEST_CODE_STATE_TAG = "android:target_req_state";
390    static final String TARGET_STATE_TAG = "android:target_state";
391    static final String VIEW_STATE_TAG = "android:view_state";
392    static final String USER_VISIBLE_HINT_TAG = "android:user_visible_hint";
393
394    ArrayList<Runnable> mPendingActions;
395    Runnable[] mTmpActions;
396    boolean mExecutingActions;
397
398    ArrayList<Fragment> mActive;
399    ArrayList<Fragment> mAdded;
400    ArrayList<Integer> mAvailIndices;
401    ArrayList<BackStackRecord> mBackStack;
402    ArrayList<Fragment> mCreatedMenus;
403
404    // Must be accessed while locked.
405    ArrayList<BackStackRecord> mBackStackIndices;
406    ArrayList<Integer> mAvailBackStackIndices;
407
408    ArrayList<OnBackStackChangedListener> mBackStackChangeListeners;
409
410    int mCurState = Fragment.INITIALIZING;
411    Activity mActivity;
412
413    boolean mNeedMenuInvalidate;
414    boolean mStateSaved;
415    boolean mDestroyed;
416    String mNoTransactionsBecause;
417    boolean mHavePendingDeferredStart;
418
419    // Temporary vars for state save and restore.
420    Bundle mStateBundle = null;
421    SparseArray<Parcelable> mStateArray = null;
422
423    Runnable mExecCommit = new Runnable() {
424        @Override
425        public void run() {
426            execPendingActions();
427        }
428    };
429
430    @Override
431    public FragmentTransaction beginTransaction() {
432        return new BackStackRecord(this);
433    }
434
435    @Override
436    public boolean executePendingTransactions() {
437        return execPendingActions();
438    }
439
440    @Override
441    public void popBackStack() {
442        enqueueAction(new Runnable() {
443            @Override public void run() {
444                popBackStackState(mActivity.mHandler, null, -1, 0);
445            }
446        }, false);
447    }
448
449    @Override
450    public boolean popBackStackImmediate() {
451        checkStateLoss();
452        executePendingTransactions();
453        return popBackStackState(mActivity.mHandler, null, -1, 0);
454    }
455
456    @Override
457    public void popBackStack(final String name, final int flags) {
458        enqueueAction(new Runnable() {
459            @Override public void run() {
460                popBackStackState(mActivity.mHandler, name, -1, flags);
461            }
462        }, false);
463    }
464
465    @Override
466    public boolean popBackStackImmediate(String name, int flags) {
467        checkStateLoss();
468        executePendingTransactions();
469        return popBackStackState(mActivity.mHandler, name, -1, flags);
470    }
471
472    @Override
473    public void popBackStack(final int id, final int flags) {
474        if (id < 0) {
475            throw new IllegalArgumentException("Bad id: " + id);
476        }
477        enqueueAction(new Runnable() {
478            @Override public void run() {
479                popBackStackState(mActivity.mHandler, null, id, flags);
480            }
481        }, false);
482    }
483
484    @Override
485    public boolean popBackStackImmediate(int id, int flags) {
486        checkStateLoss();
487        executePendingTransactions();
488        if (id < 0) {
489            throw new IllegalArgumentException("Bad id: " + id);
490        }
491        return popBackStackState(mActivity.mHandler, null, id, flags);
492    }
493
494    @Override
495    public int getBackStackEntryCount() {
496        return mBackStack != null ? mBackStack.size() : 0;
497    }
498
499    @Override
500    public BackStackEntry getBackStackEntryAt(int index) {
501        return mBackStack.get(index);
502    }
503
504    @Override
505    public void addOnBackStackChangedListener(OnBackStackChangedListener listener) {
506        if (mBackStackChangeListeners == null) {
507            mBackStackChangeListeners = new ArrayList<OnBackStackChangedListener>();
508        }
509        mBackStackChangeListeners.add(listener);
510    }
511
512    @Override
513    public void removeOnBackStackChangedListener(OnBackStackChangedListener listener) {
514        if (mBackStackChangeListeners != null) {
515            mBackStackChangeListeners.remove(listener);
516        }
517    }
518
519    @Override
520    public void putFragment(Bundle bundle, String key, Fragment fragment) {
521        if (fragment.mIndex < 0) {
522            throw new IllegalStateException("Fragment " + fragment
523                    + " is not currently in the FragmentManager");
524        }
525        bundle.putInt(key, fragment.mIndex);
526    }
527
528    @Override
529    public Fragment getFragment(Bundle bundle, String key) {
530        int index = bundle.getInt(key, -1);
531        if (index == -1) {
532            return null;
533        }
534        if (index >= mActive.size()) {
535            throw new IllegalStateException("Fragement no longer exists for key "
536                    + key + ": index " + index);
537        }
538        Fragment f = mActive.get(index);
539        if (f == null) {
540            throw new IllegalStateException("Fragement no longer exists for key "
541                    + key + ": index " + index);
542        }
543        return f;
544    }
545
546    @Override
547    public Fragment.SavedState saveFragmentInstanceState(Fragment fragment) {
548        if (fragment.mIndex < 0) {
549            throw new IllegalStateException("Fragment " + fragment
550                    + " is not currently in the FragmentManager");
551        }
552        if (fragment.mState > Fragment.INITIALIZING) {
553            Bundle result = saveFragmentBasicState(fragment);
554            return result != null ? new Fragment.SavedState(result) : null;
555        }
556        return null;
557    }
558
559    @Override
560    public String toString() {
561        StringBuilder sb = new StringBuilder(128);
562        sb.append("FragmentManager{");
563        sb.append(Integer.toHexString(System.identityHashCode(this)));
564        sb.append(" in ");
565        DebugUtils.buildShortClassTag(mActivity, sb);
566        sb.append("}}");
567        return sb.toString();
568    }
569
570    @Override
571    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
572        String innerPrefix = prefix + "    ";
573
574        int N;
575        if (mActive != null) {
576            N = mActive.size();
577            if (N > 0) {
578                writer.print(prefix); writer.print("Active Fragments in ");
579                        writer.print(Integer.toHexString(System.identityHashCode(this)));
580                        writer.println(":");
581                for (int i=0; i<N; i++) {
582                    Fragment f = mActive.get(i);
583                    writer.print(prefix); writer.print("  #"); writer.print(i);
584                            writer.print(": "); writer.println(f);
585                    if (f != null) {
586                        f.dump(innerPrefix, fd, writer, args);
587                    }
588                }
589            }
590        }
591
592        if (mAdded != null) {
593            N = mAdded.size();
594            if (N > 0) {
595                writer.print(prefix); writer.println("Added Fragments:");
596                for (int i=0; i<N; i++) {
597                    Fragment f = mAdded.get(i);
598                    writer.print(prefix); writer.print("  #"); writer.print(i);
599                            writer.print(": "); writer.println(f.toString());
600                }
601            }
602        }
603
604        if (mCreatedMenus != null) {
605            N = mCreatedMenus.size();
606            if (N > 0) {
607                writer.print(prefix); writer.println("Fragments Created Menus:");
608                for (int i=0; i<N; i++) {
609                    Fragment f = mCreatedMenus.get(i);
610                    writer.print(prefix); writer.print("  #"); writer.print(i);
611                            writer.print(": "); writer.println(f.toString());
612                }
613            }
614        }
615
616        if (mBackStack != null) {
617            N = mBackStack.size();
618            if (N > 0) {
619                writer.print(prefix); writer.println("Back Stack:");
620                for (int i=0; i<N; i++) {
621                    BackStackRecord bs = mBackStack.get(i);
622                    writer.print(prefix); writer.print("  #"); writer.print(i);
623                            writer.print(": "); writer.println(bs.toString());
624                    bs.dump(innerPrefix, fd, writer, args);
625                }
626            }
627        }
628
629        synchronized (this) {
630            if (mBackStackIndices != null) {
631                N = mBackStackIndices.size();
632                if (N > 0) {
633                    writer.print(prefix); writer.println("Back Stack Indices:");
634                    for (int i=0; i<N; i++) {
635                        BackStackRecord bs = mBackStackIndices.get(i);
636                        writer.print(prefix); writer.print("  #"); writer.print(i);
637                                writer.print(": "); writer.println(bs);
638                    }
639                }
640            }
641
642            if (mAvailBackStackIndices != null && mAvailBackStackIndices.size() > 0) {
643                writer.print(prefix); writer.print("mAvailBackStackIndices: ");
644                        writer.println(Arrays.toString(mAvailBackStackIndices.toArray()));
645            }
646        }
647
648        if (mPendingActions != null) {
649            N = mPendingActions.size();
650            if (N > 0) {
651                writer.print(prefix); writer.println("Pending Actions:");
652                for (int i=0; i<N; i++) {
653                    Runnable r = mPendingActions.get(i);
654                    writer.print(prefix); writer.print("  #"); writer.print(i);
655                            writer.print(": "); writer.println(r);
656                }
657            }
658        }
659
660        writer.print(prefix); writer.println("FragmentManager misc state:");
661        writer.print(prefix); writer.print("  mCurState="); writer.print(mCurState);
662                writer.print(" mStateSaved="); writer.print(mStateSaved);
663                writer.print(" mDestroyed="); writer.println(mDestroyed);
664        if (mNeedMenuInvalidate) {
665            writer.print(prefix); writer.print("  mNeedMenuInvalidate=");
666                    writer.println(mNeedMenuInvalidate);
667        }
668        if (mNoTransactionsBecause != null) {
669            writer.print(prefix); writer.print("  mNoTransactionsBecause=");
670                    writer.println(mNoTransactionsBecause);
671        }
672        if (mAvailIndices != null && mAvailIndices.size() > 0) {
673            writer.print(prefix); writer.print("  mAvailIndices: ");
674                    writer.println(Arrays.toString(mAvailIndices.toArray()));
675        }
676    }
677
678    Animator loadAnimator(Fragment fragment, int transit, boolean enter,
679            int transitionStyle) {
680        Animator animObj = fragment.onCreateAnimator(transit, enter,
681                fragment.mNextAnim);
682        if (animObj != null) {
683            return animObj;
684        }
685
686        if (fragment.mNextAnim != 0) {
687            Animator anim = AnimatorInflater.loadAnimator(mActivity, fragment.mNextAnim);
688            if (anim != null) {
689                return anim;
690            }
691        }
692
693        if (transit == 0) {
694            return null;
695        }
696
697        int styleIndex = transitToStyleIndex(transit, enter);
698        if (styleIndex < 0) {
699            return null;
700        }
701
702        if (transitionStyle == 0 && mActivity.getWindow() != null) {
703            transitionStyle = mActivity.getWindow().getAttributes().windowAnimations;
704        }
705        if (transitionStyle == 0) {
706            return null;
707        }
708
709        TypedArray attrs = mActivity.obtainStyledAttributes(transitionStyle,
710                com.android.internal.R.styleable.FragmentAnimation);
711        int anim = attrs.getResourceId(styleIndex, 0);
712        attrs.recycle();
713
714        if (anim == 0) {
715            return null;
716        }
717
718        return AnimatorInflater.loadAnimator(mActivity, anim);
719    }
720
721    public void performPendingDeferredStart(Fragment f) {
722        if (f.mDeferStart) {
723            if (mExecutingActions) {
724                // Wait until we're done executing our pending transactions
725                mHavePendingDeferredStart = true;
726                return;
727            }
728            f.mDeferStart = false;
729            moveToState(f, mCurState, 0, 0, false);
730        }
731    }
732
733    void moveToState(Fragment f, int newState, int transit, int transitionStyle,
734            boolean keepActive) {
735        // Fragments that are not currently added will sit in the onCreate() state.
736        if (!f.mAdded && newState > Fragment.CREATED) {
737            newState = Fragment.CREATED;
738        }
739        if (f.mRemoving && newState > f.mState) {
740            // While removing a fragment, we can't change it to a higher state.
741            newState = f.mState;
742        }
743        // Defer start if requested; don't allow it to move to STARTED or higher
744        // if it's not already started.
745        if (f.mDeferStart && f.mState < Fragment.STARTED && newState > Fragment.STOPPED) {
746            newState = Fragment.STOPPED;
747        }
748        if (f.mState < newState) {
749            // For fragments that are created from a layout, when restoring from
750            // state we don't want to allow them to be created until they are
751            // being reloaded from the layout.
752            if (f.mFromLayout && !f.mInLayout) {
753                return;
754            }
755            if (f.mAnimatingAway != null) {
756                // The fragment is currently being animated...  but!  Now we
757                // want to move our state back up.  Give up on waiting for the
758                // animation, move to whatever the final state should be once
759                // the animation is done, and then we can proceed from there.
760                f.mAnimatingAway = null;
761                moveToState(f, f.mStateAfterAnimating, 0, 0, true);
762            }
763            switch (f.mState) {
764                case Fragment.INITIALIZING:
765                    if (DEBUG) Log.v(TAG, "moveto CREATED: " + f);
766                    if (f.mSavedFragmentState != null) {
767                        f.mSavedViewState = f.mSavedFragmentState.getSparseParcelableArray(
768                                FragmentManagerImpl.VIEW_STATE_TAG);
769                        f.mTarget = getFragment(f.mSavedFragmentState,
770                                FragmentManagerImpl.TARGET_STATE_TAG);
771                        if (f.mTarget != null) {
772                            f.mTargetRequestCode = f.mSavedFragmentState.getInt(
773                                    FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG, 0);
774                        }
775                        f.mUserVisibleHint = f.mSavedFragmentState.getBoolean(
776                                FragmentManagerImpl.USER_VISIBLE_HINT_TAG, true);
777                        if (!f.mUserVisibleHint) {
778                            f.mDeferStart = true;
779                            if (newState > Fragment.STOPPED) {
780                                newState = Fragment.STOPPED;
781                            }
782                        }
783                    }
784                    f.mActivity = mActivity;
785                    f.mFragmentManager = mActivity.mFragments;
786                    f.mCalled = false;
787                    f.onAttach(mActivity);
788                    if (!f.mCalled) {
789                        throw new SuperNotCalledException("Fragment " + f
790                                + " did not call through to super.onAttach()");
791                    }
792                    mActivity.onAttachFragment(f);
793
794                    if (!f.mRetaining) {
795                        f.mCalled = false;
796                        f.onCreate(f.mSavedFragmentState);
797                        if (!f.mCalled) {
798                            throw new SuperNotCalledException("Fragment " + f
799                                    + " did not call through to super.onCreate()");
800                        }
801                    }
802                    f.mRetaining = false;
803                    if (f.mFromLayout) {
804                        // For fragments that are part of the content view
805                        // layout, we need to instantiate the view immediately
806                        // and the inflater will take care of adding it.
807                        f.mView = f.onCreateView(f.getLayoutInflater(f.mSavedFragmentState),
808                                null, f.mSavedFragmentState);
809                        if (f.mView != null) {
810                            f.mView.setSaveFromParentEnabled(false);
811                            if (f.mHidden) f.mView.setVisibility(View.GONE);
812                            f.onViewCreated(f.mView, f.mSavedFragmentState);
813                        }
814                    }
815                case Fragment.CREATED:
816                    if (newState > Fragment.CREATED) {
817                        if (DEBUG) Log.v(TAG, "moveto ACTIVITY_CREATED: " + f);
818                        if (!f.mFromLayout) {
819                            ViewGroup container = null;
820                            if (f.mContainerId != 0) {
821                                container = (ViewGroup)mActivity.findViewById(f.mContainerId);
822                                if (container == null && !f.mRestored) {
823                                    throw new IllegalArgumentException("No view found for id 0x"
824                                            + Integer.toHexString(f.mContainerId)
825                                            + " for fragment " + f);
826                                }
827                            }
828                            f.mContainer = container;
829                            f.mView = f.onCreateView(f.getLayoutInflater(f.mSavedFragmentState),
830                                    container, f.mSavedFragmentState);
831                            if (f.mView != null) {
832                                f.mView.setSaveFromParentEnabled(false);
833                                if (container != null) {
834                                    Animator anim = loadAnimator(f, transit, true,
835                                            transitionStyle);
836                                    if (anim != null) {
837                                        anim.setTarget(f.mView);
838                                        anim.start();
839                                    }
840                                    container.addView(f.mView);
841                                }
842                                if (f.mHidden) f.mView.setVisibility(View.GONE);
843                                f.onViewCreated(f.mView, f.mSavedFragmentState);
844                            }
845                        }
846
847                        f.mCalled = false;
848                        f.onActivityCreated(f.mSavedFragmentState);
849                        if (!f.mCalled) {
850                            throw new SuperNotCalledException("Fragment " + f
851                                    + " did not call through to super.onActivityCreated()");
852                        }
853                        if (f.mView != null) {
854                            f.restoreViewState();
855                        }
856                        f.mSavedFragmentState = null;
857                    }
858                case Fragment.ACTIVITY_CREATED:
859                case Fragment.STOPPED:
860                    if (newState > Fragment.STOPPED) {
861                        if (DEBUG) Log.v(TAG, "moveto STARTED: " + f);
862                        f.mCalled = false;
863                        f.performStart();
864                        if (!f.mCalled) {
865                            throw new SuperNotCalledException("Fragment " + f
866                                    + " did not call through to super.onStart()");
867                        }
868                    }
869                case Fragment.STARTED:
870                    if (newState > Fragment.STARTED) {
871                        if (DEBUG) Log.v(TAG, "moveto RESUMED: " + f);
872                        f.mCalled = false;
873                        f.mResumed = true;
874                        f.onResume();
875                        if (!f.mCalled) {
876                            throw new SuperNotCalledException("Fragment " + f
877                                    + " did not call through to super.onResume()");
878                        }
879                        // Get rid of this in case we saved it and never needed it.
880                        f.mSavedFragmentState = null;
881                        f.mSavedViewState = null;
882                    }
883            }
884        } else if (f.mState > newState) {
885            switch (f.mState) {
886                case Fragment.RESUMED:
887                    if (newState < Fragment.RESUMED) {
888                        if (DEBUG) Log.v(TAG, "movefrom RESUMED: " + f);
889                        f.mCalled = false;
890                        f.onPause();
891                        if (!f.mCalled) {
892                            throw new SuperNotCalledException("Fragment " + f
893                                    + " did not call through to super.onPause()");
894                        }
895                        f.mResumed = false;
896                    }
897                case Fragment.STARTED:
898                    if (newState < Fragment.STARTED) {
899                        if (DEBUG) Log.v(TAG, "movefrom STARTED: " + f);
900                        f.mCalled = false;
901                        f.performStop();
902                        if (!f.mCalled) {
903                            throw new SuperNotCalledException("Fragment " + f
904                                    + " did not call through to super.onStop()");
905                        }
906                    }
907                case Fragment.STOPPED:
908                case Fragment.ACTIVITY_CREATED:
909                    if (newState < Fragment.ACTIVITY_CREATED) {
910                        if (DEBUG) Log.v(TAG, "movefrom ACTIVITY_CREATED: " + f);
911                        if (f.mView != null) {
912                            // Need to save the current view state if not
913                            // done already.
914                            if (!mActivity.isFinishing() && f.mSavedViewState == null) {
915                                saveFragmentViewState(f);
916                            }
917                        }
918                        f.mCalled = false;
919                        f.performDestroyView();
920                        if (!f.mCalled) {
921                            throw new SuperNotCalledException("Fragment " + f
922                                    + " did not call through to super.onDestroyView()");
923                        }
924                        if (f.mView != null && f.mContainer != null) {
925                            Animator anim = null;
926                            if (mCurState > Fragment.INITIALIZING && !mDestroyed) {
927                                anim = loadAnimator(f, transit, false,
928                                        transitionStyle);
929                            }
930                            if (anim != null) {
931                                final ViewGroup container = f.mContainer;
932                                final View view = f.mView;
933                                final Fragment fragment = f;
934                                container.startViewTransition(view);
935                                f.mAnimatingAway = anim;
936                                f.mStateAfterAnimating = newState;
937                                anim.addListener(new AnimatorListenerAdapter() {
938                                    @Override
939                                    public void onAnimationEnd(Animator anim) {
940                                        container.endViewTransition(view);
941                                        if (fragment.mAnimatingAway != null) {
942                                            fragment.mAnimatingAway = null;
943                                            moveToState(fragment, fragment.mStateAfterAnimating,
944                                                    0, 0, false);
945                                        }
946                                    }
947                                });
948                                anim.setTarget(f.mView);
949                                anim.start();
950
951                            }
952                            f.mContainer.removeView(f.mView);
953                        }
954                        f.mContainer = null;
955                        f.mView = null;
956                    }
957                case Fragment.CREATED:
958                    if (newState < Fragment.CREATED) {
959                        if (mDestroyed) {
960                            if (f.mAnimatingAway != null) {
961                                // The fragment's containing activity is
962                                // being destroyed, but this fragment is
963                                // currently animating away.  Stop the
964                                // animation right now -- it is not needed,
965                                // and we can't wait any more on destroying
966                                // the fragment.
967                                Animator anim = f.mAnimatingAway;
968                                f.mAnimatingAway = null;
969                                anim.cancel();
970                            }
971                        }
972                        if (f.mAnimatingAway != null) {
973                            // We are waiting for the fragment's view to finish
974                            // animating away.  Just make a note of the state
975                            // the fragment now should move to once the animation
976                            // is done.
977                            f.mStateAfterAnimating = newState;
978                            newState = Fragment.CREATED;
979                        } else {
980                            if (DEBUG) Log.v(TAG, "movefrom CREATED: " + f);
981                            if (!f.mRetaining) {
982                                f.mCalled = false;
983                                f.onDestroy();
984                                if (!f.mCalled) {
985                                    throw new SuperNotCalledException("Fragment " + f
986                                            + " did not call through to super.onDestroy()");
987                                }
988                            }
989
990                            f.mCalled = false;
991                            f.onDetach();
992                            if (!f.mCalled) {
993                                throw new SuperNotCalledException("Fragment " + f
994                                        + " did not call through to super.onDetach()");
995                            }
996                            if (!keepActive) {
997                                if (!f.mRetaining) {
998                                    makeInactive(f);
999                                } else {
1000                                    f.mActivity = null;
1001                                    f.mFragmentManager = null;
1002                                }
1003                            }
1004                        }
1005                    }
1006            }
1007        }
1008
1009        f.mState = newState;
1010    }
1011
1012    void moveToState(Fragment f) {
1013        moveToState(f, mCurState, 0, 0, false);
1014    }
1015
1016    void moveToState(int newState, boolean always) {
1017        moveToState(newState, 0, 0, always);
1018    }
1019
1020    void moveToState(int newState, int transit, int transitStyle, boolean always) {
1021        if (mActivity == null && newState != Fragment.INITIALIZING) {
1022            throw new IllegalStateException("No activity");
1023        }
1024
1025        if (!always && mCurState == newState) {
1026            return;
1027        }
1028
1029        mCurState = newState;
1030        if (mActive != null) {
1031            boolean loadersRunning = false;
1032            for (int i=0; i<mActive.size(); i++) {
1033                Fragment f = mActive.get(i);
1034                if (f != null) {
1035                    moveToState(f, newState, transit, transitStyle, false);
1036                    if (f.mLoaderManager != null) {
1037                        loadersRunning |= f.mLoaderManager.hasRunningLoaders();
1038                    }
1039                }
1040            }
1041
1042            if (!loadersRunning) {
1043                startPendingDeferredFragments();
1044            }
1045
1046            if (mNeedMenuInvalidate && mActivity != null && mCurState == Fragment.RESUMED) {
1047                mActivity.invalidateOptionsMenu();
1048                mNeedMenuInvalidate = false;
1049            }
1050        }
1051    }
1052
1053    void startPendingDeferredFragments() {
1054        if (mActive == null) return;
1055
1056        for (int i=0; i<mActive.size(); i++) {
1057            Fragment f = mActive.get(i);
1058            if (f != null) {
1059                performPendingDeferredStart(f);
1060            }
1061        }
1062    }
1063
1064    void makeActive(Fragment f) {
1065        if (f.mIndex >= 0) {
1066            return;
1067        }
1068
1069        if (mAvailIndices == null || mAvailIndices.size() <= 0) {
1070            if (mActive == null) {
1071                mActive = new ArrayList<Fragment>();
1072            }
1073            f.setIndex(mActive.size());
1074            mActive.add(f);
1075
1076        } else {
1077            f.setIndex(mAvailIndices.remove(mAvailIndices.size()-1));
1078            mActive.set(f.mIndex, f);
1079        }
1080        if (DEBUG) Log.v(TAG, "Allocated fragment index " + f);
1081    }
1082
1083    void makeInactive(Fragment f) {
1084        if (f.mIndex < 0) {
1085            return;
1086        }
1087
1088        if (DEBUG) Log.v(TAG, "Freeing fragment index " + f);
1089        mActive.set(f.mIndex, null);
1090        if (mAvailIndices == null) {
1091            mAvailIndices = new ArrayList<Integer>();
1092        }
1093        mAvailIndices.add(f.mIndex);
1094        mActivity.invalidateFragmentIndex(f.mIndex);
1095        f.initState();
1096    }
1097
1098    public void addFragment(Fragment fragment, boolean moveToStateNow) {
1099        if (mAdded == null) {
1100            mAdded = new ArrayList<Fragment>();
1101        }
1102        if (DEBUG) Log.v(TAG, "add: " + fragment);
1103        makeActive(fragment);
1104        if (!fragment.mDetached) {
1105            mAdded.add(fragment);
1106            fragment.mAdded = true;
1107            fragment.mRemoving = false;
1108            if (fragment.mHasMenu && fragment.mMenuVisible) {
1109                mNeedMenuInvalidate = true;
1110            }
1111            if (moveToStateNow) {
1112                moveToState(fragment);
1113            }
1114        }
1115    }
1116
1117    public void removeFragment(Fragment fragment, int transition, int transitionStyle) {
1118        if (DEBUG) Log.v(TAG, "remove: " + fragment + " nesting=" + fragment.mBackStackNesting);
1119        final boolean inactive = !fragment.isInBackStack();
1120        if (!fragment.mDetached || inactive) {
1121            mAdded.remove(fragment);
1122            if (fragment.mHasMenu && fragment.mMenuVisible) {
1123                mNeedMenuInvalidate = true;
1124            }
1125            fragment.mAdded = false;
1126            fragment.mRemoving = true;
1127            moveToState(fragment, inactive ? Fragment.INITIALIZING : Fragment.CREATED,
1128                    transition, transitionStyle, false);
1129        }
1130    }
1131
1132    public void hideFragment(Fragment fragment, int transition, int transitionStyle) {
1133        if (DEBUG) Log.v(TAG, "hide: " + fragment);
1134        if (!fragment.mHidden) {
1135            fragment.mHidden = true;
1136            if (fragment.mView != null) {
1137                Animator anim = loadAnimator(fragment, transition, true,
1138                        transitionStyle);
1139                if (anim != null) {
1140                    anim.setTarget(fragment.mView);
1141                    // Delay the actual hide operation until the animation finishes, otherwise
1142                    // the fragment will just immediately disappear
1143                    final Fragment finalFragment = fragment;
1144                    anim.addListener(new AnimatorListenerAdapter() {
1145                        @Override
1146                        public void onAnimationEnd(Animator animation) {
1147                            if (finalFragment.mView != null) {
1148                                finalFragment.mView.setVisibility(View.GONE);
1149                            }
1150                        }
1151                    });
1152                    anim.start();
1153                } else {
1154                    fragment.mView.setVisibility(View.GONE);
1155                }
1156            }
1157            if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) {
1158                mNeedMenuInvalidate = true;
1159            }
1160            fragment.onHiddenChanged(true);
1161        }
1162    }
1163
1164    public void showFragment(Fragment fragment, int transition, int transitionStyle) {
1165        if (DEBUG) Log.v(TAG, "show: " + fragment);
1166        if (fragment.mHidden) {
1167            fragment.mHidden = false;
1168            if (fragment.mView != null) {
1169                Animator anim = loadAnimator(fragment, transition, true,
1170                        transitionStyle);
1171                if (anim != null) {
1172                    anim.setTarget(fragment.mView);
1173                    anim.start();
1174                }
1175                fragment.mView.setVisibility(View.VISIBLE);
1176            }
1177            if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) {
1178                mNeedMenuInvalidate = true;
1179            }
1180            fragment.onHiddenChanged(false);
1181        }
1182    }
1183
1184    public void detachFragment(Fragment fragment, int transition, int transitionStyle) {
1185        if (DEBUG) Log.v(TAG, "detach: " + fragment);
1186        if (!fragment.mDetached) {
1187            fragment.mDetached = true;
1188            if (fragment.mAdded) {
1189                // We are not already in back stack, so need to remove the fragment.
1190                mAdded.remove(fragment);
1191                if (fragment.mHasMenu && fragment.mMenuVisible) {
1192                    mNeedMenuInvalidate = true;
1193                }
1194                fragment.mAdded = false;
1195                moveToState(fragment, Fragment.CREATED, transition, transitionStyle, false);
1196            }
1197        }
1198    }
1199
1200    public void attachFragment(Fragment fragment, int transition, int transitionStyle) {
1201        if (DEBUG) Log.v(TAG, "attach: " + fragment);
1202        if (fragment.mDetached) {
1203            fragment.mDetached = false;
1204            if (!fragment.mAdded) {
1205                mAdded.add(fragment);
1206                fragment.mAdded = true;
1207                if (fragment.mHasMenu && fragment.mMenuVisible) {
1208                    mNeedMenuInvalidate = true;
1209                }
1210                moveToState(fragment, mCurState, transition, transitionStyle, false);
1211            }
1212        }
1213    }
1214
1215    public Fragment findFragmentById(int id) {
1216        if (mActive != null) {
1217            // First look through added fragments.
1218            for (int i=mAdded.size()-1; i>=0; i--) {
1219                Fragment f = mAdded.get(i);
1220                if (f != null && f.mFragmentId == id) {
1221                    return f;
1222                }
1223            }
1224            // Now for any known fragment.
1225            for (int i=mActive.size()-1; i>=0; i--) {
1226                Fragment f = mActive.get(i);
1227                if (f != null && f.mFragmentId == id) {
1228                    return f;
1229                }
1230            }
1231        }
1232        return null;
1233    }
1234
1235    public Fragment findFragmentByTag(String tag) {
1236        if (mActive != null && tag != null) {
1237            // First look through added fragments.
1238            for (int i=mAdded.size()-1; i>=0; i--) {
1239                Fragment f = mAdded.get(i);
1240                if (f != null && tag.equals(f.mTag)) {
1241                    return f;
1242                }
1243            }
1244            // Now for any known fragment.
1245            for (int i=mActive.size()-1; i>=0; i--) {
1246                Fragment f = mActive.get(i);
1247                if (f != null && tag.equals(f.mTag)) {
1248                    return f;
1249                }
1250            }
1251        }
1252        return null;
1253    }
1254
1255    public Fragment findFragmentByWho(String who) {
1256        if (mActive != null && who != null) {
1257            for (int i=mActive.size()-1; i>=0; i--) {
1258                Fragment f = mActive.get(i);
1259                if (f != null && who.equals(f.mWho)) {
1260                    return f;
1261                }
1262            }
1263        }
1264        return null;
1265    }
1266
1267    private void checkStateLoss() {
1268        if (mStateSaved) {
1269            throw new IllegalStateException(
1270                    "Can not perform this action after onSaveInstanceState");
1271        }
1272        if (mNoTransactionsBecause != null) {
1273            throw new IllegalStateException(
1274                    "Can not perform this action inside of " + mNoTransactionsBecause);
1275        }
1276    }
1277
1278    public void enqueueAction(Runnable action, boolean allowStateLoss) {
1279        if (!allowStateLoss) {
1280            checkStateLoss();
1281        }
1282        synchronized (this) {
1283            if (mActivity == null) {
1284                throw new IllegalStateException("Activity has been destroyed");
1285            }
1286            if (mPendingActions == null) {
1287                mPendingActions = new ArrayList<Runnable>();
1288            }
1289            mPendingActions.add(action);
1290            if (mPendingActions.size() == 1) {
1291                mActivity.mHandler.removeCallbacks(mExecCommit);
1292                mActivity.mHandler.post(mExecCommit);
1293            }
1294        }
1295    }
1296
1297    public int allocBackStackIndex(BackStackRecord bse) {
1298        synchronized (this) {
1299            if (mAvailBackStackIndices == null || mAvailBackStackIndices.size() <= 0) {
1300                if (mBackStackIndices == null) {
1301                    mBackStackIndices = new ArrayList<BackStackRecord>();
1302                }
1303                int index = mBackStackIndices.size();
1304                if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse);
1305                mBackStackIndices.add(bse);
1306                return index;
1307
1308            } else {
1309                int index = mAvailBackStackIndices.remove(mAvailBackStackIndices.size()-1);
1310                if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse);
1311                mBackStackIndices.set(index, bse);
1312                return index;
1313            }
1314        }
1315    }
1316
1317    public void setBackStackIndex(int index, BackStackRecord bse) {
1318        synchronized (this) {
1319            if (mBackStackIndices == null) {
1320                mBackStackIndices = new ArrayList<BackStackRecord>();
1321            }
1322            int N = mBackStackIndices.size();
1323            if (index < N) {
1324                if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse);
1325                mBackStackIndices.set(index, bse);
1326            } else {
1327                while (N < index) {
1328                    mBackStackIndices.add(null);
1329                    if (mAvailBackStackIndices == null) {
1330                        mAvailBackStackIndices = new ArrayList<Integer>();
1331                    }
1332                    if (DEBUG) Log.v(TAG, "Adding available back stack index " + N);
1333                    mAvailBackStackIndices.add(N);
1334                    N++;
1335                }
1336                if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse);
1337                mBackStackIndices.add(bse);
1338            }
1339        }
1340    }
1341
1342    public void freeBackStackIndex(int index) {
1343        synchronized (this) {
1344            mBackStackIndices.set(index, null);
1345            if (mAvailBackStackIndices == null) {
1346                mAvailBackStackIndices = new ArrayList<Integer>();
1347            }
1348            if (DEBUG) Log.v(TAG, "Freeing back stack index " + index);
1349            mAvailBackStackIndices.add(index);
1350        }
1351    }
1352
1353    /**
1354     * Only call from main thread!
1355     */
1356    public boolean execPendingActions() {
1357        if (mExecutingActions) {
1358            throw new IllegalStateException("Recursive entry to executePendingTransactions");
1359        }
1360
1361        if (Looper.myLooper() != mActivity.mHandler.getLooper()) {
1362            throw new IllegalStateException("Must be called from main thread of process");
1363        }
1364
1365        boolean didSomething = false;
1366
1367        while (true) {
1368            int numActions;
1369
1370            synchronized (this) {
1371                if (mPendingActions == null || mPendingActions.size() == 0) {
1372                    break;
1373                }
1374
1375                numActions = mPendingActions.size();
1376                if (mTmpActions == null || mTmpActions.length < numActions) {
1377                    mTmpActions = new Runnable[numActions];
1378                }
1379                mPendingActions.toArray(mTmpActions);
1380                mPendingActions.clear();
1381                mActivity.mHandler.removeCallbacks(mExecCommit);
1382            }
1383
1384            mExecutingActions = true;
1385            for (int i=0; i<numActions; i++) {
1386                mTmpActions[i].run();
1387                mTmpActions[i] = null;
1388            }
1389            mExecutingActions = false;
1390            didSomething = true;
1391        }
1392
1393        if (mHavePendingDeferredStart) {
1394            boolean loadersRunning = false;
1395            for (int i=0; i<mActive.size(); i++) {
1396                Fragment f = mActive.get(i);
1397                if (f != null && f.mLoaderManager != null) {
1398                    loadersRunning |= f.mLoaderManager.hasRunningLoaders();
1399                }
1400            }
1401            if (!loadersRunning) {
1402                mHavePendingDeferredStart = false;
1403                startPendingDeferredFragments();
1404            }
1405        }
1406        return didSomething;
1407    }
1408
1409    void reportBackStackChanged() {
1410        if (mBackStackChangeListeners != null) {
1411            for (int i=0; i<mBackStackChangeListeners.size(); i++) {
1412                mBackStackChangeListeners.get(i).onBackStackChanged();
1413            }
1414        }
1415    }
1416
1417    void addBackStackState(BackStackRecord state) {
1418        if (mBackStack == null) {
1419            mBackStack = new ArrayList<BackStackRecord>();
1420        }
1421        mBackStack.add(state);
1422        reportBackStackChanged();
1423    }
1424
1425    boolean popBackStackState(Handler handler, String name, int id, int flags) {
1426        if (mBackStack == null) {
1427            return false;
1428        }
1429        if (name == null && id < 0 && (flags&POP_BACK_STACK_INCLUSIVE) == 0) {
1430            int last = mBackStack.size()-1;
1431            if (last < 0) {
1432                return false;
1433            }
1434            final BackStackRecord bss = mBackStack.remove(last);
1435            bss.popFromBackStack(true);
1436            reportBackStackChanged();
1437        } else {
1438            int index = -1;
1439            if (name != null || id >= 0) {
1440                // If a name or ID is specified, look for that place in
1441                // the stack.
1442                index = mBackStack.size()-1;
1443                while (index >= 0) {
1444                    BackStackRecord bss = mBackStack.get(index);
1445                    if (name != null && name.equals(bss.getName())) {
1446                        break;
1447                    }
1448                    if (id >= 0 && id == bss.mIndex) {
1449                        break;
1450                    }
1451                    index--;
1452                }
1453                if (index < 0) {
1454                    return false;
1455                }
1456                if ((flags&POP_BACK_STACK_INCLUSIVE) != 0) {
1457                    index--;
1458                    // Consume all following entries that match.
1459                    while (index >= 0) {
1460                        BackStackRecord bss = mBackStack.get(index);
1461                        if ((name != null && name.equals(bss.getName()))
1462                                || (id >= 0 && id == bss.mIndex)) {
1463                            index--;
1464                            continue;
1465                        }
1466                        break;
1467                    }
1468                }
1469            }
1470            if (index == mBackStack.size()-1) {
1471                return false;
1472            }
1473            final ArrayList<BackStackRecord> states
1474                    = new ArrayList<BackStackRecord>();
1475            for (int i=mBackStack.size()-1; i>index; i--) {
1476                states.add(mBackStack.remove(i));
1477            }
1478            final int LAST = states.size()-1;
1479            for (int i=0; i<=LAST; i++) {
1480                if (DEBUG) Log.v(TAG, "Popping back stack state: " + states.get(i));
1481                states.get(i).popFromBackStack(i == LAST);
1482            }
1483            reportBackStackChanged();
1484        }
1485        return true;
1486    }
1487
1488    ArrayList<Fragment> retainNonConfig() {
1489        ArrayList<Fragment> fragments = null;
1490        if (mActive != null) {
1491            for (int i=0; i<mActive.size(); i++) {
1492                Fragment f = mActive.get(i);
1493                if (f != null && f.mRetainInstance) {
1494                    if (fragments == null) {
1495                        fragments = new ArrayList<Fragment>();
1496                    }
1497                    fragments.add(f);
1498                    f.mRetaining = true;
1499                    f.mTargetIndex = f.mTarget != null ? f.mTarget.mIndex : -1;
1500                    if (DEBUG) Log.v(TAG, "retainNonConfig: keeping retained " + f);
1501                }
1502            }
1503        }
1504        return fragments;
1505    }
1506
1507    void saveFragmentViewState(Fragment f) {
1508        if (f.mView == null) {
1509            return;
1510        }
1511        if (mStateArray == null) {
1512            mStateArray = new SparseArray<Parcelable>();
1513        } else {
1514            mStateArray.clear();
1515        }
1516        f.mView.saveHierarchyState(mStateArray);
1517        if (mStateArray.size() > 0) {
1518            f.mSavedViewState = mStateArray;
1519            mStateArray = null;
1520        }
1521    }
1522
1523    Bundle saveFragmentBasicState(Fragment f) {
1524        Bundle result = null;
1525
1526        if (mStateBundle == null) {
1527            mStateBundle = new Bundle();
1528        }
1529        f.onSaveInstanceState(mStateBundle);
1530        if (!mStateBundle.isEmpty()) {
1531            result = mStateBundle;
1532            mStateBundle = null;
1533        }
1534
1535        if (f.mView != null) {
1536            saveFragmentViewState(f);
1537        }
1538        if (f.mSavedViewState != null) {
1539            if (result == null) {
1540                result = new Bundle();
1541            }
1542            result.putSparseParcelableArray(
1543                    FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState);
1544        }
1545        if (!f.mUserVisibleHint) {
1546            if (result == null) {
1547                result = new Bundle();
1548            }
1549            // Only add this if it's not the default value
1550            result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint);
1551        }
1552
1553        return result;
1554    }
1555
1556    Parcelable saveAllState() {
1557        // Make sure all pending operations have now been executed to get
1558        // our state update-to-date.
1559        execPendingActions();
1560
1561        mStateSaved = true;
1562
1563        if (mActive == null || mActive.size() <= 0) {
1564            return null;
1565        }
1566
1567        // First collect all active fragments.
1568        int N = mActive.size();
1569        FragmentState[] active = new FragmentState[N];
1570        boolean haveFragments = false;
1571        for (int i=0; i<N; i++) {
1572            Fragment f = mActive.get(i);
1573            if (f != null) {
1574                if (f.mIndex < 0) {
1575                    String msg = "Failure saving state: active " + f
1576                            + " has cleared index: " + f.mIndex;
1577                    Slog.e(TAG, msg);
1578                    dump("  ", null, new PrintWriter(new LogWriter(
1579                            Log.ERROR, TAG, Log.LOG_ID_SYSTEM)), new String[] { });
1580                    throw new IllegalStateException(msg);
1581                }
1582
1583                haveFragments = true;
1584
1585                FragmentState fs = new FragmentState(f);
1586                active[i] = fs;
1587
1588                if (f.mState > Fragment.INITIALIZING && fs.mSavedFragmentState == null) {
1589                    fs.mSavedFragmentState = saveFragmentBasicState(f);
1590
1591                    if (f.mTarget != null) {
1592                        if (f.mTarget.mIndex < 0) {
1593                            String msg = "Failure saving state: " + f
1594                                + " has target not in fragment manager: " + f.mTarget;
1595                            Slog.e(TAG, msg);
1596                            dump("  ", null, new PrintWriter(new LogWriter(
1597                                    Log.ERROR, TAG, Log.LOG_ID_SYSTEM)), new String[] { });
1598                            throw new IllegalStateException(msg);
1599                        }
1600                        if (fs.mSavedFragmentState == null) {
1601                            fs.mSavedFragmentState = new Bundle();
1602                        }
1603                        putFragment(fs.mSavedFragmentState,
1604                                FragmentManagerImpl.TARGET_STATE_TAG, f.mTarget);
1605                        if (f.mTargetRequestCode != 0) {
1606                            fs.mSavedFragmentState.putInt(
1607                                    FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG,
1608                                    f.mTargetRequestCode);
1609                        }
1610                    }
1611
1612                } else {
1613                    fs.mSavedFragmentState = f.mSavedFragmentState;
1614                }
1615
1616                if (DEBUG) Log.v(TAG, "Saved state of " + f + ": "
1617                        + fs.mSavedFragmentState);
1618            }
1619        }
1620
1621        if (!haveFragments) {
1622            if (DEBUG) Log.v(TAG, "saveAllState: no fragments!");
1623            return null;
1624        }
1625
1626        int[] added = null;
1627        BackStackState[] backStack = null;
1628
1629        // Build list of currently added fragments.
1630        if (mAdded != null) {
1631            N = mAdded.size();
1632            if (N > 0) {
1633                added = new int[N];
1634                for (int i=0; i<N; i++) {
1635                    added[i] = mAdded.get(i).mIndex;
1636                    if (added[i] < 0) {
1637                        String msg = "Failure saving state: active " + mAdded.get(i)
1638                                + " has cleared index: " + added[i];
1639                        Slog.e(TAG, msg);
1640                        dump("  ", null, new PrintWriter(new LogWriter(
1641                                Log.ERROR, TAG, Log.LOG_ID_SYSTEM)), new String[] { });
1642                        throw new IllegalStateException(msg);
1643                    }
1644                    if (DEBUG) Log.v(TAG, "saveAllState: adding fragment #" + i
1645                            + ": " + mAdded.get(i));
1646                }
1647            }
1648        }
1649
1650        // Now save back stack.
1651        if (mBackStack != null) {
1652            N = mBackStack.size();
1653            if (N > 0) {
1654                backStack = new BackStackState[N];
1655                for (int i=0; i<N; i++) {
1656                    backStack[i] = new BackStackState(this, mBackStack.get(i));
1657                    if (DEBUG) Log.v(TAG, "saveAllState: adding back stack #" + i
1658                            + ": " + mBackStack.get(i));
1659                }
1660            }
1661        }
1662
1663        FragmentManagerState fms = new FragmentManagerState();
1664        fms.mActive = active;
1665        fms.mAdded = added;
1666        fms.mBackStack = backStack;
1667        return fms;
1668    }
1669
1670    void restoreAllState(Parcelable state, ArrayList<Fragment> nonConfig) {
1671        // If there is no saved state at all, then there can not be
1672        // any nonConfig fragments either, so that is that.
1673        if (state == null) return;
1674        FragmentManagerState fms = (FragmentManagerState)state;
1675        if (fms.mActive == null) return;
1676
1677        // First re-attach any non-config instances we are retaining back
1678        // to their saved state, so we don't try to instantiate them again.
1679        if (nonConfig != null) {
1680            for (int i=0; i<nonConfig.size(); i++) {
1681                Fragment f = nonConfig.get(i);
1682                if (DEBUG) Log.v(TAG, "restoreAllState: re-attaching retained " + f);
1683                FragmentState fs = fms.mActive[f.mIndex];
1684                fs.mInstance = f;
1685                f.mSavedViewState = null;
1686                f.mBackStackNesting = 0;
1687                f.mInLayout = false;
1688                f.mAdded = false;
1689                f.mTarget = null;
1690                if (fs.mSavedFragmentState != null) {
1691                    fs.mSavedFragmentState.setClassLoader(mActivity.getClassLoader());
1692                    f.mSavedViewState = fs.mSavedFragmentState.getSparseParcelableArray(
1693                            FragmentManagerImpl.VIEW_STATE_TAG);
1694                }
1695            }
1696        }
1697
1698        // Build the full list of active fragments, instantiating them from
1699        // their saved state.
1700        mActive = new ArrayList<Fragment>(fms.mActive.length);
1701        if (mAvailIndices != null) {
1702            mAvailIndices.clear();
1703        }
1704        for (int i=0; i<fms.mActive.length; i++) {
1705            FragmentState fs = fms.mActive[i];
1706            if (fs != null) {
1707                Fragment f = fs.instantiate(mActivity);
1708                if (DEBUG) Log.v(TAG, "restoreAllState: adding #" + i + ": " + f);
1709                mActive.add(f);
1710                // Now that the fragment is instantiated (or came from being
1711                // retained above), clear mInstance in case we end up re-restoring
1712                // from this FragmentState again.
1713                fs.mInstance = null;
1714            } else {
1715                if (DEBUG) Log.v(TAG, "restoreAllState: adding #" + i + ": (null)");
1716                mActive.add(null);
1717                if (mAvailIndices == null) {
1718                    mAvailIndices = new ArrayList<Integer>();
1719                }
1720                if (DEBUG) Log.v(TAG, "restoreAllState: adding avail #" + i);
1721                mAvailIndices.add(i);
1722            }
1723        }
1724
1725        // Update the target of all retained fragments.
1726        if (nonConfig != null) {
1727            for (int i=0; i<nonConfig.size(); i++) {
1728                Fragment f = nonConfig.get(i);
1729                if (f.mTargetIndex >= 0) {
1730                    if (f.mTargetIndex < mActive.size()) {
1731                        f.mTarget = mActive.get(f.mTargetIndex);
1732                    } else {
1733                        Log.w(TAG, "Re-attaching retained fragment " + f
1734                                + " target no longer exists: " + f.mTargetIndex);
1735                        f.mTarget = null;
1736                    }
1737                }
1738            }
1739        }
1740
1741        // Build the list of currently added fragments.
1742        if (fms.mAdded != null) {
1743            mAdded = new ArrayList<Fragment>(fms.mAdded.length);
1744            for (int i=0; i<fms.mAdded.length; i++) {
1745                Fragment f = mActive.get(fms.mAdded[i]);
1746                if (f == null) {
1747                    throw new IllegalStateException(
1748                            "No instantiated fragment for index #" + fms.mAdded[i]);
1749                }
1750                f.mAdded = true;
1751                if (DEBUG) Log.v(TAG, "restoreAllState: making added #" + i + ": " + f);
1752                mAdded.add(f);
1753            }
1754        } else {
1755            mAdded = null;
1756        }
1757
1758        // Build the back stack.
1759        if (fms.mBackStack != null) {
1760            mBackStack = new ArrayList<BackStackRecord>(fms.mBackStack.length);
1761            for (int i=0; i<fms.mBackStack.length; i++) {
1762                BackStackRecord bse = fms.mBackStack[i].instantiate(this);
1763                if (DEBUG) Log.v(TAG, "restoreAllState: adding bse #" + i
1764                        + " (index " + bse.mIndex + "): " + bse);
1765                mBackStack.add(bse);
1766                if (bse.mIndex >= 0) {
1767                    setBackStackIndex(bse.mIndex, bse);
1768                }
1769            }
1770        } else {
1771            mBackStack = null;
1772        }
1773    }
1774
1775    public void attachActivity(Activity activity) {
1776        if (mActivity != null) throw new IllegalStateException();
1777        mActivity = activity;
1778    }
1779
1780    public void noteStateNotSaved() {
1781        mStateSaved = false;
1782    }
1783
1784    public void dispatchCreate() {
1785        mStateSaved = false;
1786        moveToState(Fragment.CREATED, false);
1787    }
1788
1789    public void dispatchActivityCreated() {
1790        mStateSaved = false;
1791        moveToState(Fragment.ACTIVITY_CREATED, false);
1792    }
1793
1794    public void dispatchStart() {
1795        mStateSaved = false;
1796        moveToState(Fragment.STARTED, false);
1797    }
1798
1799    public void dispatchResume() {
1800        mStateSaved = false;
1801        moveToState(Fragment.RESUMED, false);
1802    }
1803
1804    public void dispatchPause() {
1805        moveToState(Fragment.STARTED, false);
1806    }
1807
1808    public void dispatchStop() {
1809        moveToState(Fragment.STOPPED, false);
1810    }
1811
1812    public void dispatchDestroy() {
1813        mDestroyed = true;
1814        execPendingActions();
1815        moveToState(Fragment.INITIALIZING, false);
1816        mActivity = null;
1817    }
1818
1819    public void dispatchConfigurationChanged(Configuration newConfig) {
1820        if (mActive != null) {
1821            for (int i=0; i<mAdded.size(); i++) {
1822                Fragment f = mAdded.get(i);
1823                if (f != null) {
1824                    f.onConfigurationChanged(newConfig);
1825                }
1826            }
1827        }
1828    }
1829
1830    public void dispatchLowMemory() {
1831        if (mActive != null) {
1832            for (int i=0; i<mAdded.size(); i++) {
1833                Fragment f = mAdded.get(i);
1834                if (f != null) {
1835                    f.onLowMemory();
1836                }
1837            }
1838        }
1839    }
1840
1841    public void dispatchTrimMemory(int level) {
1842        if (mActive != null) {
1843            for (int i=0; i<mAdded.size(); i++) {
1844                Fragment f = mAdded.get(i);
1845                if (f != null) {
1846                    f.onTrimMemory(level);
1847                }
1848            }
1849        }
1850    }
1851
1852    public boolean dispatchCreateOptionsMenu(Menu menu, MenuInflater inflater) {
1853        boolean show = false;
1854        ArrayList<Fragment> newMenus = null;
1855        if (mActive != null) {
1856            for (int i=0; i<mAdded.size(); i++) {
1857                Fragment f = mAdded.get(i);
1858                if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible) {
1859                    show = true;
1860                    f.onCreateOptionsMenu(menu, inflater);
1861                    if (newMenus == null) {
1862                        newMenus = new ArrayList<Fragment>();
1863                    }
1864                    newMenus.add(f);
1865                }
1866            }
1867        }
1868
1869        if (mCreatedMenus != null) {
1870            for (int i=0; i<mCreatedMenus.size(); i++) {
1871                Fragment f = mCreatedMenus.get(i);
1872                if (newMenus == null || !newMenus.contains(f)) {
1873                    f.onDestroyOptionsMenu();
1874                }
1875            }
1876        }
1877
1878        mCreatedMenus = newMenus;
1879
1880        return show;
1881    }
1882
1883    public boolean dispatchPrepareOptionsMenu(Menu menu) {
1884        boolean show = false;
1885        if (mActive != null) {
1886            for (int i=0; i<mAdded.size(); i++) {
1887                Fragment f = mAdded.get(i);
1888                if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible) {
1889                    show = true;
1890                    f.onPrepareOptionsMenu(menu);
1891                }
1892            }
1893        }
1894        return show;
1895    }
1896
1897    public boolean dispatchOptionsItemSelected(MenuItem item) {
1898        if (mActive != null) {
1899            for (int i=0; i<mAdded.size(); i++) {
1900                Fragment f = mAdded.get(i);
1901                if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible) {
1902                    if (f.onOptionsItemSelected(item)) {
1903                        return true;
1904                    }
1905                }
1906            }
1907        }
1908        return false;
1909    }
1910
1911    public boolean dispatchContextItemSelected(MenuItem item) {
1912        if (mActive != null) {
1913            for (int i=0; i<mAdded.size(); i++) {
1914                Fragment f = mAdded.get(i);
1915                if (f != null && !f.mHidden) {
1916                    if (f.onContextItemSelected(item)) {
1917                        return true;
1918                    }
1919                }
1920            }
1921        }
1922        return false;
1923    }
1924
1925    public void dispatchOptionsMenuClosed(Menu menu) {
1926        if (mActive != null) {
1927            for (int i=0; i<mAdded.size(); i++) {
1928                Fragment f = mAdded.get(i);
1929                if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible) {
1930                    f.onOptionsMenuClosed(menu);
1931                }
1932            }
1933        }
1934    }
1935
1936    @Override
1937    public void invalidateOptionsMenu() {
1938        if (mActivity != null && mCurState == Fragment.RESUMED) {
1939            mActivity.invalidateOptionsMenu();
1940        } else {
1941            mNeedMenuInvalidate = true;
1942        }
1943    }
1944
1945    public static int reverseTransit(int transit) {
1946        int rev = 0;
1947        switch (transit) {
1948            case FragmentTransaction.TRANSIT_FRAGMENT_OPEN:
1949                rev = FragmentTransaction.TRANSIT_FRAGMENT_CLOSE;
1950                break;
1951            case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE:
1952                rev = FragmentTransaction.TRANSIT_FRAGMENT_OPEN;
1953                break;
1954            case FragmentTransaction.TRANSIT_FRAGMENT_FADE:
1955                rev = FragmentTransaction.TRANSIT_FRAGMENT_FADE;
1956                break;
1957        }
1958        return rev;
1959
1960    }
1961
1962    public static int transitToStyleIndex(int transit, boolean enter) {
1963        int animAttr = -1;
1964        switch (transit) {
1965            case FragmentTransaction.TRANSIT_FRAGMENT_OPEN:
1966                animAttr = enter
1967                    ? com.android.internal.R.styleable.FragmentAnimation_fragmentOpenEnterAnimation
1968                    : com.android.internal.R.styleable.FragmentAnimation_fragmentOpenExitAnimation;
1969                break;
1970            case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE:
1971                animAttr = enter
1972                    ? com.android.internal.R.styleable.FragmentAnimation_fragmentCloseEnterAnimation
1973                    : com.android.internal.R.styleable.FragmentAnimation_fragmentCloseExitAnimation;
1974                break;
1975            case FragmentTransaction.TRANSIT_FRAGMENT_FADE:
1976                animAttr = enter
1977                    ? com.android.internal.R.styleable.FragmentAnimation_fragmentFadeEnterAnimation
1978                    : com.android.internal.R.styleable.FragmentAnimation_fragmentFadeExitAnimation;
1979                break;
1980        }
1981        return animAttr;
1982    }
1983}
1984