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