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