FragmentManager.java revision ae5bd3a998fb0b811f2575899514e73243041a5d
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            if (mAdded != null) {
1122                mAdded.remove(fragment);
1123            }
1124            if (fragment.mHasMenu && fragment.mMenuVisible) {
1125                mNeedMenuInvalidate = true;
1126            }
1127            fragment.mAdded = false;
1128            fragment.mRemoving = true;
1129            moveToState(fragment, inactive ? Fragment.INITIALIZING : Fragment.CREATED,
1130                    transition, transitionStyle, false);
1131        }
1132    }
1133
1134    public void hideFragment(Fragment fragment, int transition, int transitionStyle) {
1135        if (DEBUG) Log.v(TAG, "hide: " + fragment);
1136        if (!fragment.mHidden) {
1137            fragment.mHidden = true;
1138            if (fragment.mView != null) {
1139                Animator anim = loadAnimator(fragment, transition, true,
1140                        transitionStyle);
1141                if (anim != null) {
1142                    anim.setTarget(fragment.mView);
1143                    // Delay the actual hide operation until the animation finishes, otherwise
1144                    // the fragment will just immediately disappear
1145                    final Fragment finalFragment = fragment;
1146                    anim.addListener(new AnimatorListenerAdapter() {
1147                        @Override
1148                        public void onAnimationEnd(Animator animation) {
1149                            if (finalFragment.mView != null) {
1150                                finalFragment.mView.setVisibility(View.GONE);
1151                            }
1152                        }
1153                    });
1154                    anim.start();
1155                } else {
1156                    fragment.mView.setVisibility(View.GONE);
1157                }
1158            }
1159            if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) {
1160                mNeedMenuInvalidate = true;
1161            }
1162            fragment.onHiddenChanged(true);
1163        }
1164    }
1165
1166    public void showFragment(Fragment fragment, int transition, int transitionStyle) {
1167        if (DEBUG) Log.v(TAG, "show: " + fragment);
1168        if (fragment.mHidden) {
1169            fragment.mHidden = false;
1170            if (fragment.mView != null) {
1171                Animator anim = loadAnimator(fragment, transition, true,
1172                        transitionStyle);
1173                if (anim != null) {
1174                    anim.setTarget(fragment.mView);
1175                    anim.start();
1176                }
1177                fragment.mView.setVisibility(View.VISIBLE);
1178            }
1179            if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) {
1180                mNeedMenuInvalidate = true;
1181            }
1182            fragment.onHiddenChanged(false);
1183        }
1184    }
1185
1186    public void detachFragment(Fragment fragment, int transition, int transitionStyle) {
1187        if (DEBUG) Log.v(TAG, "detach: " + fragment);
1188        if (!fragment.mDetached) {
1189            fragment.mDetached = true;
1190            if (fragment.mAdded) {
1191                // We are not already in back stack, so need to remove the fragment.
1192                if (mAdded != null) {
1193                    mAdded.remove(fragment);
1194                }
1195                if (fragment.mHasMenu && fragment.mMenuVisible) {
1196                    mNeedMenuInvalidate = true;
1197                }
1198                fragment.mAdded = false;
1199                moveToState(fragment, Fragment.CREATED, transition, transitionStyle, false);
1200            }
1201        }
1202    }
1203
1204    public void attachFragment(Fragment fragment, int transition, int transitionStyle) {
1205        if (DEBUG) Log.v(TAG, "attach: " + fragment);
1206        if (fragment.mDetached) {
1207            fragment.mDetached = false;
1208            if (!fragment.mAdded) {
1209                if (mAdded == null) {
1210                    mAdded = new ArrayList<Fragment>();
1211                }
1212                mAdded.add(fragment);
1213                fragment.mAdded = true;
1214                if (fragment.mHasMenu && fragment.mMenuVisible) {
1215                    mNeedMenuInvalidate = true;
1216                }
1217                moveToState(fragment, mCurState, transition, transitionStyle, false);
1218            }
1219        }
1220    }
1221
1222    public Fragment findFragmentById(int id) {
1223        if (mAdded != null) {
1224            // First look through added fragments.
1225            for (int i=mAdded.size()-1; i>=0; i--) {
1226                Fragment f = mAdded.get(i);
1227                if (f != null && f.mFragmentId == id) {
1228                    return f;
1229                }
1230            }
1231        }
1232        if (mActive != null) {
1233            // Now for any known fragment.
1234            for (int i=mActive.size()-1; i>=0; i--) {
1235                Fragment f = mActive.get(i);
1236                if (f != null && f.mFragmentId == id) {
1237                    return f;
1238                }
1239            }
1240        }
1241        return null;
1242    }
1243
1244    public Fragment findFragmentByTag(String tag) {
1245        if (mAdded != null && tag != null) {
1246            // First look through added fragments.
1247            for (int i=mAdded.size()-1; i>=0; i--) {
1248                Fragment f = mAdded.get(i);
1249                if (f != null && tag.equals(f.mTag)) {
1250                    return f;
1251                }
1252            }
1253        }
1254        if (mActive != null && tag != null) {
1255            // Now for any known fragment.
1256            for (int i=mActive.size()-1; i>=0; i--) {
1257                Fragment f = mActive.get(i);
1258                if (f != null && tag.equals(f.mTag)) {
1259                    return f;
1260                }
1261            }
1262        }
1263        return null;
1264    }
1265
1266    public Fragment findFragmentByWho(String who) {
1267        if (mActive != null && who != null) {
1268            for (int i=mActive.size()-1; i>=0; i--) {
1269                Fragment f = mActive.get(i);
1270                if (f != null && who.equals(f.mWho)) {
1271                    return f;
1272                }
1273            }
1274        }
1275        return null;
1276    }
1277
1278    private void checkStateLoss() {
1279        if (mStateSaved) {
1280            throw new IllegalStateException(
1281                    "Can not perform this action after onSaveInstanceState");
1282        }
1283        if (mNoTransactionsBecause != null) {
1284            throw new IllegalStateException(
1285                    "Can not perform this action inside of " + mNoTransactionsBecause);
1286        }
1287    }
1288
1289    public void enqueueAction(Runnable action, boolean allowStateLoss) {
1290        if (!allowStateLoss) {
1291            checkStateLoss();
1292        }
1293        synchronized (this) {
1294            if (mActivity == null) {
1295                throw new IllegalStateException("Activity has been destroyed");
1296            }
1297            if (mPendingActions == null) {
1298                mPendingActions = new ArrayList<Runnable>();
1299            }
1300            mPendingActions.add(action);
1301            if (mPendingActions.size() == 1) {
1302                mActivity.mHandler.removeCallbacks(mExecCommit);
1303                mActivity.mHandler.post(mExecCommit);
1304            }
1305        }
1306    }
1307
1308    public int allocBackStackIndex(BackStackRecord bse) {
1309        synchronized (this) {
1310            if (mAvailBackStackIndices == null || mAvailBackStackIndices.size() <= 0) {
1311                if (mBackStackIndices == null) {
1312                    mBackStackIndices = new ArrayList<BackStackRecord>();
1313                }
1314                int index = mBackStackIndices.size();
1315                if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse);
1316                mBackStackIndices.add(bse);
1317                return index;
1318
1319            } else {
1320                int index = mAvailBackStackIndices.remove(mAvailBackStackIndices.size()-1);
1321                if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse);
1322                mBackStackIndices.set(index, bse);
1323                return index;
1324            }
1325        }
1326    }
1327
1328    public void setBackStackIndex(int index, BackStackRecord bse) {
1329        synchronized (this) {
1330            if (mBackStackIndices == null) {
1331                mBackStackIndices = new ArrayList<BackStackRecord>();
1332            }
1333            int N = mBackStackIndices.size();
1334            if (index < N) {
1335                if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse);
1336                mBackStackIndices.set(index, bse);
1337            } else {
1338                while (N < index) {
1339                    mBackStackIndices.add(null);
1340                    if (mAvailBackStackIndices == null) {
1341                        mAvailBackStackIndices = new ArrayList<Integer>();
1342                    }
1343                    if (DEBUG) Log.v(TAG, "Adding available back stack index " + N);
1344                    mAvailBackStackIndices.add(N);
1345                    N++;
1346                }
1347                if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse);
1348                mBackStackIndices.add(bse);
1349            }
1350        }
1351    }
1352
1353    public void freeBackStackIndex(int index) {
1354        synchronized (this) {
1355            mBackStackIndices.set(index, null);
1356            if (mAvailBackStackIndices == null) {
1357                mAvailBackStackIndices = new ArrayList<Integer>();
1358            }
1359            if (DEBUG) Log.v(TAG, "Freeing back stack index " + index);
1360            mAvailBackStackIndices.add(index);
1361        }
1362    }
1363
1364    /**
1365     * Only call from main thread!
1366     */
1367    public boolean execPendingActions() {
1368        if (mExecutingActions) {
1369            throw new IllegalStateException("Recursive entry to executePendingTransactions");
1370        }
1371
1372        if (Looper.myLooper() != mActivity.mHandler.getLooper()) {
1373            throw new IllegalStateException("Must be called from main thread of process");
1374        }
1375
1376        boolean didSomething = false;
1377
1378        while (true) {
1379            int numActions;
1380
1381            synchronized (this) {
1382                if (mPendingActions == null || mPendingActions.size() == 0) {
1383                    break;
1384                }
1385
1386                numActions = mPendingActions.size();
1387                if (mTmpActions == null || mTmpActions.length < numActions) {
1388                    mTmpActions = new Runnable[numActions];
1389                }
1390                mPendingActions.toArray(mTmpActions);
1391                mPendingActions.clear();
1392                mActivity.mHandler.removeCallbacks(mExecCommit);
1393            }
1394
1395            mExecutingActions = true;
1396            for (int i=0; i<numActions; i++) {
1397                mTmpActions[i].run();
1398                mTmpActions[i] = null;
1399            }
1400            mExecutingActions = false;
1401            didSomething = true;
1402        }
1403
1404        if (mHavePendingDeferredStart) {
1405            boolean loadersRunning = false;
1406            for (int i=0; i<mActive.size(); i++) {
1407                Fragment f = mActive.get(i);
1408                if (f != null && f.mLoaderManager != null) {
1409                    loadersRunning |= f.mLoaderManager.hasRunningLoaders();
1410                }
1411            }
1412            if (!loadersRunning) {
1413                mHavePendingDeferredStart = false;
1414                startPendingDeferredFragments();
1415            }
1416        }
1417        return didSomething;
1418    }
1419
1420    void reportBackStackChanged() {
1421        if (mBackStackChangeListeners != null) {
1422            for (int i=0; i<mBackStackChangeListeners.size(); i++) {
1423                mBackStackChangeListeners.get(i).onBackStackChanged();
1424            }
1425        }
1426    }
1427
1428    void addBackStackState(BackStackRecord state) {
1429        if (mBackStack == null) {
1430            mBackStack = new ArrayList<BackStackRecord>();
1431        }
1432        mBackStack.add(state);
1433        reportBackStackChanged();
1434    }
1435
1436    boolean popBackStackState(Handler handler, String name, int id, int flags) {
1437        if (mBackStack == null) {
1438            return false;
1439        }
1440        if (name == null && id < 0 && (flags&POP_BACK_STACK_INCLUSIVE) == 0) {
1441            int last = mBackStack.size()-1;
1442            if (last < 0) {
1443                return false;
1444            }
1445            final BackStackRecord bss = mBackStack.remove(last);
1446            bss.popFromBackStack(true);
1447            reportBackStackChanged();
1448        } else {
1449            int index = -1;
1450            if (name != null || id >= 0) {
1451                // If a name or ID is specified, look for that place in
1452                // the stack.
1453                index = mBackStack.size()-1;
1454                while (index >= 0) {
1455                    BackStackRecord bss = mBackStack.get(index);
1456                    if (name != null && name.equals(bss.getName())) {
1457                        break;
1458                    }
1459                    if (id >= 0 && id == bss.mIndex) {
1460                        break;
1461                    }
1462                    index--;
1463                }
1464                if (index < 0) {
1465                    return false;
1466                }
1467                if ((flags&POP_BACK_STACK_INCLUSIVE) != 0) {
1468                    index--;
1469                    // Consume all following entries that match.
1470                    while (index >= 0) {
1471                        BackStackRecord bss = mBackStack.get(index);
1472                        if ((name != null && name.equals(bss.getName()))
1473                                || (id >= 0 && id == bss.mIndex)) {
1474                            index--;
1475                            continue;
1476                        }
1477                        break;
1478                    }
1479                }
1480            }
1481            if (index == mBackStack.size()-1) {
1482                return false;
1483            }
1484            final ArrayList<BackStackRecord> states
1485                    = new ArrayList<BackStackRecord>();
1486            for (int i=mBackStack.size()-1; i>index; i--) {
1487                states.add(mBackStack.remove(i));
1488            }
1489            final int LAST = states.size()-1;
1490            for (int i=0; i<=LAST; i++) {
1491                if (DEBUG) Log.v(TAG, "Popping back stack state: " + states.get(i));
1492                states.get(i).popFromBackStack(i == LAST);
1493            }
1494            reportBackStackChanged();
1495        }
1496        return true;
1497    }
1498
1499    ArrayList<Fragment> retainNonConfig() {
1500        ArrayList<Fragment> fragments = null;
1501        if (mActive != null) {
1502            for (int i=0; i<mActive.size(); i++) {
1503                Fragment f = mActive.get(i);
1504                if (f != null && f.mRetainInstance) {
1505                    if (fragments == null) {
1506                        fragments = new ArrayList<Fragment>();
1507                    }
1508                    fragments.add(f);
1509                    f.mRetaining = true;
1510                    f.mTargetIndex = f.mTarget != null ? f.mTarget.mIndex : -1;
1511                    if (DEBUG) Log.v(TAG, "retainNonConfig: keeping retained " + f);
1512                }
1513            }
1514        }
1515        return fragments;
1516    }
1517
1518    void saveFragmentViewState(Fragment f) {
1519        if (f.mView == null) {
1520            return;
1521        }
1522        if (mStateArray == null) {
1523            mStateArray = new SparseArray<Parcelable>();
1524        } else {
1525            mStateArray.clear();
1526        }
1527        f.mView.saveHierarchyState(mStateArray);
1528        if (mStateArray.size() > 0) {
1529            f.mSavedViewState = mStateArray;
1530            mStateArray = null;
1531        }
1532    }
1533
1534    Bundle saveFragmentBasicState(Fragment f) {
1535        Bundle result = null;
1536
1537        if (mStateBundle == null) {
1538            mStateBundle = new Bundle();
1539        }
1540        f.onSaveInstanceState(mStateBundle);
1541        if (!mStateBundle.isEmpty()) {
1542            result = mStateBundle;
1543            mStateBundle = null;
1544        }
1545
1546        if (f.mView != null) {
1547            saveFragmentViewState(f);
1548        }
1549        if (f.mSavedViewState != null) {
1550            if (result == null) {
1551                result = new Bundle();
1552            }
1553            result.putSparseParcelableArray(
1554                    FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState);
1555        }
1556        if (!f.mUserVisibleHint) {
1557            if (result == null) {
1558                result = new Bundle();
1559            }
1560            // Only add this if it's not the default value
1561            result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint);
1562        }
1563
1564        return result;
1565    }
1566
1567    Parcelable saveAllState() {
1568        // Make sure all pending operations have now been executed to get
1569        // our state update-to-date.
1570        execPendingActions();
1571
1572        mStateSaved = true;
1573
1574        if (mActive == null || mActive.size() <= 0) {
1575            return null;
1576        }
1577
1578        // First collect all active fragments.
1579        int N = mActive.size();
1580        FragmentState[] active = new FragmentState[N];
1581        boolean haveFragments = false;
1582        for (int i=0; i<N; i++) {
1583            Fragment f = mActive.get(i);
1584            if (f != null) {
1585                if (f.mIndex < 0) {
1586                    String msg = "Failure saving state: active " + f
1587                            + " has cleared index: " + f.mIndex;
1588                    Slog.e(TAG, msg);
1589                    dump("  ", null, new PrintWriter(new LogWriter(
1590                            Log.ERROR, TAG, Log.LOG_ID_SYSTEM)), new String[] { });
1591                    throw new IllegalStateException(msg);
1592                }
1593
1594                haveFragments = true;
1595
1596                FragmentState fs = new FragmentState(f);
1597                active[i] = fs;
1598
1599                if (f.mState > Fragment.INITIALIZING && fs.mSavedFragmentState == null) {
1600                    fs.mSavedFragmentState = saveFragmentBasicState(f);
1601
1602                    if (f.mTarget != null) {
1603                        if (f.mTarget.mIndex < 0) {
1604                            String msg = "Failure saving state: " + f
1605                                + " has target not in fragment manager: " + f.mTarget;
1606                            Slog.e(TAG, msg);
1607                            dump("  ", null, new PrintWriter(new LogWriter(
1608                                    Log.ERROR, TAG, Log.LOG_ID_SYSTEM)), new String[] { });
1609                            throw new IllegalStateException(msg);
1610                        }
1611                        if (fs.mSavedFragmentState == null) {
1612                            fs.mSavedFragmentState = new Bundle();
1613                        }
1614                        putFragment(fs.mSavedFragmentState,
1615                                FragmentManagerImpl.TARGET_STATE_TAG, f.mTarget);
1616                        if (f.mTargetRequestCode != 0) {
1617                            fs.mSavedFragmentState.putInt(
1618                                    FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG,
1619                                    f.mTargetRequestCode);
1620                        }
1621                    }
1622
1623                } else {
1624                    fs.mSavedFragmentState = f.mSavedFragmentState;
1625                }
1626
1627                if (DEBUG) Log.v(TAG, "Saved state of " + f + ": "
1628                        + fs.mSavedFragmentState);
1629            }
1630        }
1631
1632        if (!haveFragments) {
1633            if (DEBUG) Log.v(TAG, "saveAllState: no fragments!");
1634            return null;
1635        }
1636
1637        int[] added = null;
1638        BackStackState[] backStack = null;
1639
1640        // Build list of currently added fragments.
1641        if (mAdded != null) {
1642            N = mAdded.size();
1643            if (N > 0) {
1644                added = new int[N];
1645                for (int i=0; i<N; i++) {
1646                    added[i] = mAdded.get(i).mIndex;
1647                    if (added[i] < 0) {
1648                        String msg = "Failure saving state: active " + mAdded.get(i)
1649                                + " has cleared index: " + added[i];
1650                        Slog.e(TAG, msg);
1651                        dump("  ", null, new PrintWriter(new LogWriter(
1652                                Log.ERROR, TAG, Log.LOG_ID_SYSTEM)), new String[] { });
1653                        throw new IllegalStateException(msg);
1654                    }
1655                    if (DEBUG) Log.v(TAG, "saveAllState: adding fragment #" + i
1656                            + ": " + mAdded.get(i));
1657                }
1658            }
1659        }
1660
1661        // Now save back stack.
1662        if (mBackStack != null) {
1663            N = mBackStack.size();
1664            if (N > 0) {
1665                backStack = new BackStackState[N];
1666                for (int i=0; i<N; i++) {
1667                    backStack[i] = new BackStackState(this, mBackStack.get(i));
1668                    if (DEBUG) Log.v(TAG, "saveAllState: adding back stack #" + i
1669                            + ": " + mBackStack.get(i));
1670                }
1671            }
1672        }
1673
1674        FragmentManagerState fms = new FragmentManagerState();
1675        fms.mActive = active;
1676        fms.mAdded = added;
1677        fms.mBackStack = backStack;
1678        return fms;
1679    }
1680
1681    void restoreAllState(Parcelable state, ArrayList<Fragment> nonConfig) {
1682        // If there is no saved state at all, then there can not be
1683        // any nonConfig fragments either, so that is that.
1684        if (state == null) return;
1685        FragmentManagerState fms = (FragmentManagerState)state;
1686        if (fms.mActive == null) return;
1687
1688        // First re-attach any non-config instances we are retaining back
1689        // to their saved state, so we don't try to instantiate them again.
1690        if (nonConfig != null) {
1691            for (int i=0; i<nonConfig.size(); i++) {
1692                Fragment f = nonConfig.get(i);
1693                if (DEBUG) Log.v(TAG, "restoreAllState: re-attaching retained " + f);
1694                FragmentState fs = fms.mActive[f.mIndex];
1695                fs.mInstance = f;
1696                f.mSavedViewState = null;
1697                f.mBackStackNesting = 0;
1698                f.mInLayout = false;
1699                f.mAdded = false;
1700                f.mTarget = null;
1701                if (fs.mSavedFragmentState != null) {
1702                    fs.mSavedFragmentState.setClassLoader(mActivity.getClassLoader());
1703                    f.mSavedViewState = fs.mSavedFragmentState.getSparseParcelableArray(
1704                            FragmentManagerImpl.VIEW_STATE_TAG);
1705                }
1706            }
1707        }
1708
1709        // Build the full list of active fragments, instantiating them from
1710        // their saved state.
1711        mActive = new ArrayList<Fragment>(fms.mActive.length);
1712        if (mAvailIndices != null) {
1713            mAvailIndices.clear();
1714        }
1715        for (int i=0; i<fms.mActive.length; i++) {
1716            FragmentState fs = fms.mActive[i];
1717            if (fs != null) {
1718                Fragment f = fs.instantiate(mActivity);
1719                if (DEBUG) Log.v(TAG, "restoreAllState: adding #" + i + ": " + f);
1720                mActive.add(f);
1721                // Now that the fragment is instantiated (or came from being
1722                // retained above), clear mInstance in case we end up re-restoring
1723                // from this FragmentState again.
1724                fs.mInstance = null;
1725            } else {
1726                if (DEBUG) Log.v(TAG, "restoreAllState: adding #" + i + ": (null)");
1727                mActive.add(null);
1728                if (mAvailIndices == null) {
1729                    mAvailIndices = new ArrayList<Integer>();
1730                }
1731                if (DEBUG) Log.v(TAG, "restoreAllState: adding avail #" + i);
1732                mAvailIndices.add(i);
1733            }
1734        }
1735
1736        // Update the target of all retained fragments.
1737        if (nonConfig != null) {
1738            for (int i=0; i<nonConfig.size(); i++) {
1739                Fragment f = nonConfig.get(i);
1740                if (f.mTargetIndex >= 0) {
1741                    if (f.mTargetIndex < mActive.size()) {
1742                        f.mTarget = mActive.get(f.mTargetIndex);
1743                    } else {
1744                        Log.w(TAG, "Re-attaching retained fragment " + f
1745                                + " target no longer exists: " + f.mTargetIndex);
1746                        f.mTarget = null;
1747                    }
1748                }
1749            }
1750        }
1751
1752        // Build the list of currently added fragments.
1753        if (fms.mAdded != null) {
1754            mAdded = new ArrayList<Fragment>(fms.mAdded.length);
1755            for (int i=0; i<fms.mAdded.length; i++) {
1756                Fragment f = mActive.get(fms.mAdded[i]);
1757                if (f == null) {
1758                    throw new IllegalStateException(
1759                            "No instantiated fragment for index #" + fms.mAdded[i]);
1760                }
1761                f.mAdded = true;
1762                if (DEBUG) Log.v(TAG, "restoreAllState: making added #" + i + ": " + f);
1763                mAdded.add(f);
1764            }
1765        } else {
1766            mAdded = null;
1767        }
1768
1769        // Build the back stack.
1770        if (fms.mBackStack != null) {
1771            mBackStack = new ArrayList<BackStackRecord>(fms.mBackStack.length);
1772            for (int i=0; i<fms.mBackStack.length; i++) {
1773                BackStackRecord bse = fms.mBackStack[i].instantiate(this);
1774                if (DEBUG) Log.v(TAG, "restoreAllState: adding bse #" + i
1775                        + " (index " + bse.mIndex + "): " + bse);
1776                mBackStack.add(bse);
1777                if (bse.mIndex >= 0) {
1778                    setBackStackIndex(bse.mIndex, bse);
1779                }
1780            }
1781        } else {
1782            mBackStack = null;
1783        }
1784    }
1785
1786    public void attachActivity(Activity activity) {
1787        if (mActivity != null) throw new IllegalStateException();
1788        mActivity = activity;
1789    }
1790
1791    public void noteStateNotSaved() {
1792        mStateSaved = false;
1793    }
1794
1795    public void dispatchCreate() {
1796        mStateSaved = false;
1797        moveToState(Fragment.CREATED, false);
1798    }
1799
1800    public void dispatchActivityCreated() {
1801        mStateSaved = false;
1802        moveToState(Fragment.ACTIVITY_CREATED, false);
1803    }
1804
1805    public void dispatchStart() {
1806        mStateSaved = false;
1807        moveToState(Fragment.STARTED, false);
1808    }
1809
1810    public void dispatchResume() {
1811        mStateSaved = false;
1812        moveToState(Fragment.RESUMED, false);
1813    }
1814
1815    public void dispatchPause() {
1816        moveToState(Fragment.STARTED, false);
1817    }
1818
1819    public void dispatchStop() {
1820        moveToState(Fragment.STOPPED, false);
1821    }
1822
1823    public void dispatchDestroy() {
1824        mDestroyed = true;
1825        execPendingActions();
1826        moveToState(Fragment.INITIALIZING, false);
1827        mActivity = null;
1828    }
1829
1830    public void dispatchConfigurationChanged(Configuration newConfig) {
1831        if (mAdded != null) {
1832            for (int i=0; i<mAdded.size(); i++) {
1833                Fragment f = mAdded.get(i);
1834                if (f != null) {
1835                    f.onConfigurationChanged(newConfig);
1836                }
1837            }
1838        }
1839    }
1840
1841    public void dispatchLowMemory() {
1842        if (mAdded != null) {
1843            for (int i=0; i<mAdded.size(); i++) {
1844                Fragment f = mAdded.get(i);
1845                if (f != null) {
1846                    f.onLowMemory();
1847                }
1848            }
1849        }
1850    }
1851
1852    public void dispatchTrimMemory(int level) {
1853        if (mAdded != null) {
1854            for (int i=0; i<mAdded.size(); i++) {
1855                Fragment f = mAdded.get(i);
1856                if (f != null) {
1857                    f.onTrimMemory(level);
1858                }
1859            }
1860        }
1861    }
1862
1863    public boolean dispatchCreateOptionsMenu(Menu menu, MenuInflater inflater) {
1864        boolean show = false;
1865        ArrayList<Fragment> newMenus = null;
1866        if (mAdded != null) {
1867            for (int i=0; i<mAdded.size(); i++) {
1868                Fragment f = mAdded.get(i);
1869                if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible) {
1870                    show = true;
1871                    f.onCreateOptionsMenu(menu, inflater);
1872                    if (newMenus == null) {
1873                        newMenus = new ArrayList<Fragment>();
1874                    }
1875                    newMenus.add(f);
1876                }
1877            }
1878        }
1879
1880        if (mCreatedMenus != null) {
1881            for (int i=0; i<mCreatedMenus.size(); i++) {
1882                Fragment f = mCreatedMenus.get(i);
1883                if (newMenus == null || !newMenus.contains(f)) {
1884                    f.onDestroyOptionsMenu();
1885                }
1886            }
1887        }
1888
1889        mCreatedMenus = newMenus;
1890
1891        return show;
1892    }
1893
1894    public boolean dispatchPrepareOptionsMenu(Menu menu) {
1895        boolean show = false;
1896        if (mAdded != null) {
1897            for (int i=0; i<mAdded.size(); i++) {
1898                Fragment f = mAdded.get(i);
1899                if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible) {
1900                    show = true;
1901                    f.onPrepareOptionsMenu(menu);
1902                }
1903            }
1904        }
1905        return show;
1906    }
1907
1908    public boolean dispatchOptionsItemSelected(MenuItem item) {
1909        if (mAdded != null) {
1910            for (int i=0; i<mAdded.size(); i++) {
1911                Fragment f = mAdded.get(i);
1912                if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible) {
1913                    if (f.onOptionsItemSelected(item)) {
1914                        return true;
1915                    }
1916                }
1917            }
1918        }
1919        return false;
1920    }
1921
1922    public boolean dispatchContextItemSelected(MenuItem item) {
1923        if (mAdded != null) {
1924            for (int i=0; i<mAdded.size(); i++) {
1925                Fragment f = mAdded.get(i);
1926                if (f != null && !f.mHidden) {
1927                    if (f.onContextItemSelected(item)) {
1928                        return true;
1929                    }
1930                }
1931            }
1932        }
1933        return false;
1934    }
1935
1936    public void dispatchOptionsMenuClosed(Menu menu) {
1937        if (mAdded != null) {
1938            for (int i=0; i<mAdded.size(); i++) {
1939                Fragment f = mAdded.get(i);
1940                if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible) {
1941                    f.onOptionsMenuClosed(menu);
1942                }
1943            }
1944        }
1945    }
1946
1947    @Override
1948    public void invalidateOptionsMenu() {
1949        if (mActivity != null && mCurState == Fragment.RESUMED) {
1950            mActivity.invalidateOptionsMenu();
1951        } else {
1952            mNeedMenuInvalidate = true;
1953        }
1954    }
1955
1956    public static int reverseTransit(int transit) {
1957        int rev = 0;
1958        switch (transit) {
1959            case FragmentTransaction.TRANSIT_FRAGMENT_OPEN:
1960                rev = FragmentTransaction.TRANSIT_FRAGMENT_CLOSE;
1961                break;
1962            case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE:
1963                rev = FragmentTransaction.TRANSIT_FRAGMENT_OPEN;
1964                break;
1965            case FragmentTransaction.TRANSIT_FRAGMENT_FADE:
1966                rev = FragmentTransaction.TRANSIT_FRAGMENT_FADE;
1967                break;
1968        }
1969        return rev;
1970
1971    }
1972
1973    public static int transitToStyleIndex(int transit, boolean enter) {
1974        int animAttr = -1;
1975        switch (transit) {
1976            case FragmentTransaction.TRANSIT_FRAGMENT_OPEN:
1977                animAttr = enter
1978                    ? com.android.internal.R.styleable.FragmentAnimation_fragmentOpenEnterAnimation
1979                    : com.android.internal.R.styleable.FragmentAnimation_fragmentOpenExitAnimation;
1980                break;
1981            case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE:
1982                animAttr = enter
1983                    ? com.android.internal.R.styleable.FragmentAnimation_fragmentCloseEnterAnimation
1984                    : com.android.internal.R.styleable.FragmentAnimation_fragmentCloseExitAnimation;
1985                break;
1986            case FragmentTransaction.TRANSIT_FRAGMENT_FADE:
1987                animAttr = enter
1988                    ? com.android.internal.R.styleable.FragmentAnimation_fragmentFadeEnterAnimation
1989                    : com.android.internal.R.styleable.FragmentAnimation_fragmentFadeExitAnimation;
1990                break;
1991        }
1992        return animAttr;
1993    }
1994}
1995