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