FragmentManager.java revision ea2c91b0198855073983b4a8437aa71cbd83872f
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                            if (f.mHidden) f.mView.setVisibility(View.GONE);
778                            f.onViewCreated(f.mView, f.mSavedFragmentState);
779                        } else {
780                            f.mInnerView = null;
781                        }
782                    }
783                case Fragment.CREATED:
784                    if (newState > Fragment.CREATED) {
785                        if (DEBUG) Log.v(TAG, "moveto ACTIVITY_CREATED: " + 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                                }
810                                if (f.mHidden) f.mView.setVisibility(View.GONE);
811                                f.onViewCreated(f.mView, f.mSavedFragmentState);
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                        if (f.mView != null) {
824                            f.restoreViewState();
825                        }
826                        f.mSavedFragmentState = null;
827                    }
828                case Fragment.ACTIVITY_CREATED:
829                case Fragment.STOPPED:
830                    if (newState > Fragment.STOPPED) {
831                        if (DEBUG) Log.v(TAG, "moveto STARTED: " + f);
832                        f.mCalled = false;
833                        f.onStart();
834                        if (!f.mCalled) {
835                            throw new SuperNotCalledException("Fragment " + f
836                                    + " did not call through to super.onStart()");
837                        }
838                    }
839                case Fragment.STARTED:
840                    if (newState > Fragment.STARTED) {
841                        if (DEBUG) Log.v(TAG, "moveto RESUMED: " + f);
842                        f.mCalled = false;
843                        f.mResumed = true;
844                        f.onResume();
845                        if (!f.mCalled) {
846                            throw new SuperNotCalledException("Fragment " + f
847                                    + " did not call through to super.onResume()");
848                        }
849                    }
850            }
851        } else if (f.mState > newState) {
852            switch (f.mState) {
853                case Fragment.RESUMED:
854                    if (newState < Fragment.RESUMED) {
855                        if (DEBUG) Log.v(TAG, "movefrom RESUMED: " + f);
856                        f.mCalled = false;
857                        f.onPause();
858                        if (!f.mCalled) {
859                            throw new SuperNotCalledException("Fragment " + f
860                                    + " did not call through to super.onPause()");
861                        }
862                        f.mResumed = false;
863                    }
864                case Fragment.STARTED:
865                    if (newState < Fragment.STARTED) {
866                        if (DEBUG) Log.v(TAG, "movefrom STARTED: " + f);
867                        f.mCalled = false;
868                        f.performStop();
869                        if (!f.mCalled) {
870                            throw new SuperNotCalledException("Fragment " + f
871                                    + " did not call through to super.onStop()");
872                        }
873                    }
874                case Fragment.STOPPED:
875                case Fragment.ACTIVITY_CREATED:
876                    if (newState < Fragment.ACTIVITY_CREATED) {
877                        if (DEBUG) Log.v(TAG, "movefrom ACTIVITY_CREATED: " + f);
878                        if (f.mView != null) {
879                            // Need to save the current view state if not
880                            // done already.
881                            if (!mActivity.isFinishing() && f.mSavedViewState == null) {
882                                saveFragmentViewState(f);
883                            }
884                        }
885                        f.mCalled = false;
886                        f.onDestroyView();
887                        if (!f.mCalled) {
888                            throw new SuperNotCalledException("Fragment " + f
889                                    + " did not call through to super.onDestroyView()");
890                        }
891                        if (f.mView != null && f.mContainer != null) {
892                            Animation anim = null;
893                            if (mCurState > Fragment.INITIALIZING && !mDestroyed) {
894                                anim = loadAnimation(f, transit, false,
895                                        transitionStyle);
896                            }
897                            if (anim != null) {
898                                final Fragment fragment = f;
899                                f.mAnimatingAway = f.mView;
900                                f.mStateAfterAnimating = newState;
901                                anim.setAnimationListener(new AnimationListener() {
902                                    @Override
903                                    public void onAnimationEnd(Animation animation) {
904                                        if (fragment.mAnimatingAway != null) {
905                                            fragment.mAnimatingAway = null;
906                                            moveToState(fragment, fragment.mStateAfterAnimating,
907                                                    0, 0);
908                                        }
909                                    }
910                                    @Override
911                                    public void onAnimationRepeat(Animation animation) {
912                                    }
913                                    @Override
914                                    public void onAnimationStart(Animation animation) {
915                                    }
916                                });
917                                f.mView.startAnimation(anim);
918                            }
919                            f.mContainer.removeView(f.mView);
920                        }
921                        f.mContainer = null;
922                        f.mView = null;
923                        f.mInnerView = null;
924                    }
925                case Fragment.CREATED:
926                    if (newState < Fragment.CREATED) {
927                        if (mDestroyed) {
928                            if (f.mAnimatingAway != null) {
929                                // The fragment's containing activity is
930                                // being destroyed, but this fragment is
931                                // currently animating away.  Stop the
932                                // animation right now -- it is not needed,
933                                // and we can't wait any more on destroying
934                                // the fragment.
935                                View v = f.mAnimatingAway;
936                                f.mAnimatingAway = null;
937                                v.clearAnimation();
938                            }
939                        }
940                        if (f.mAnimatingAway != null) {
941                            // We are waiting for the fragment's view to finish
942                            // animating away.  Just make a note of the state
943                            // the fragment now should move to once the animation
944                            // is done.
945                            f.mStateAfterAnimating = newState;
946                        } else {
947                            if (DEBUG) Log.v(TAG, "movefrom CREATED: " + f);
948                            if (!f.mRetaining) {
949                                f.mCalled = false;
950                                f.onDestroy();
951                                if (!f.mCalled) {
952                                    throw new SuperNotCalledException("Fragment " + f
953                                            + " did not call through to super.onDestroy()");
954                                }
955                            }
956
957                            f.mCalled = false;
958                            f.onDetach();
959                            if (!f.mCalled) {
960                                throw new SuperNotCalledException("Fragment " + f
961                                        + " did not call through to super.onDetach()");
962                            }
963                            f.mImmediateActivity = null;
964                            f.mActivity = null;
965                            f.mFragmentManager = null;
966                        }
967                    }
968            }
969        }
970
971        f.mState = newState;
972    }
973
974    void moveToState(Fragment f) {
975        moveToState(f, mCurState, 0, 0);
976    }
977
978    void moveToState(int newState, boolean always) {
979        moveToState(newState, 0, 0, always);
980    }
981
982    void moveToState(int newState, int transit, int transitStyle, boolean always) {
983        if (mActivity == null && newState != Fragment.INITIALIZING) {
984            throw new IllegalStateException("No activity");
985        }
986
987        if (!always && mCurState == newState) {
988            return;
989        }
990
991        mCurState = newState;
992        if (mActive != null) {
993            for (int i=0; i<mActive.size(); i++) {
994                Fragment f = mActive.get(i);
995                if (f != null) {
996                    moveToState(f, newState, transit, transitStyle);
997                }
998            }
999
1000            if (mNeedMenuInvalidate && mActivity != null) {
1001                mActivity.supportInvalidateOptionsMenu();
1002                mNeedMenuInvalidate = false;
1003            }
1004        }
1005    }
1006
1007    void makeActive(Fragment f) {
1008        if (f.mIndex >= 0) {
1009            return;
1010        }
1011
1012        if (mAvailIndices == null || mAvailIndices.size() <= 0) {
1013            if (mActive == null) {
1014                mActive = new ArrayList<Fragment>();
1015            }
1016            f.setIndex(mActive.size());
1017            mActive.add(f);
1018
1019        } else {
1020            f.setIndex(mAvailIndices.remove(mAvailIndices.size()-1));
1021            mActive.set(f.mIndex, f);
1022        }
1023    }
1024
1025    void makeInactive(Fragment f) {
1026        if (f.mIndex < 0) {
1027            return;
1028        }
1029
1030        if (DEBUG) Log.v(TAG, "Freeing fragment index " + f.mIndex);
1031        mActive.set(f.mIndex, null);
1032        if (mAvailIndices == null) {
1033            mAvailIndices = new ArrayList<Integer>();
1034        }
1035        mAvailIndices.add(f.mIndex);
1036        mActivity.invalidateSupportFragmentIndex(f.mIndex);
1037        f.clearIndex();
1038    }
1039
1040    public void addFragment(Fragment fragment, boolean moveToStateNow) {
1041        if (mAdded == null) {
1042            mAdded = new ArrayList<Fragment>();
1043        }
1044        if (DEBUG) Log.v(TAG, "add: " + fragment);
1045        makeActive(fragment);
1046        if (!fragment.mDetached) {
1047            mAdded.add(fragment);
1048            fragment.mAdded = true;
1049            fragment.mRemoving = false;
1050            if (fragment.mHasMenu) {
1051                mNeedMenuInvalidate = true;
1052            }
1053            if (moveToStateNow) {
1054                moveToState(fragment);
1055            }
1056        }
1057    }
1058
1059    public void removeFragment(Fragment fragment, int transition, int transitionStyle) {
1060        if (DEBUG) Log.v(TAG, "remove: " + fragment + " nesting=" + fragment.mBackStackNesting);
1061        final boolean inactive = !fragment.isInBackStack();
1062        if (!fragment.mDetached || inactive) {
1063            mAdded.remove(fragment);
1064            if (fragment.mHasMenu) {
1065                mNeedMenuInvalidate = true;
1066            }
1067            fragment.mAdded = false;
1068            fragment.mRemoving = true;
1069            moveToState(fragment, inactive ? Fragment.INITIALIZING : Fragment.CREATED,
1070                    transition, transitionStyle);
1071            if (inactive) {
1072                makeInactive(fragment);
1073            }
1074        }
1075    }
1076
1077    public void hideFragment(Fragment fragment, int transition, int transitionStyle) {
1078        if (DEBUG) Log.v(TAG, "hide: " + fragment);
1079        if (!fragment.mHidden) {
1080            fragment.mHidden = true;
1081            if (fragment.mView != null) {
1082                Animation anim = loadAnimation(fragment, transition, true,
1083                        transitionStyle);
1084                if (anim != null) {
1085                    fragment.mView.startAnimation(anim);
1086                }
1087                fragment.mView.setVisibility(View.GONE);
1088            }
1089            if (fragment.mAdded && fragment.mHasMenu) {
1090                mNeedMenuInvalidate = true;
1091            }
1092            fragment.onHiddenChanged(true);
1093        }
1094    }
1095
1096    public void showFragment(Fragment fragment, int transition, int transitionStyle) {
1097        if (DEBUG) Log.v(TAG, "show: " + fragment);
1098        if (fragment.mHidden) {
1099            fragment.mHidden = false;
1100            if (fragment.mView != null) {
1101                Animation anim = loadAnimation(fragment, transition, true,
1102                        transitionStyle);
1103                if (anim != null) {
1104                    fragment.mView.startAnimation(anim);
1105                }
1106                fragment.mView.setVisibility(View.VISIBLE);
1107            }
1108            if (fragment.mAdded && fragment.mHasMenu) {
1109                mNeedMenuInvalidate = true;
1110            }
1111            fragment.onHiddenChanged(false);
1112        }
1113    }
1114
1115    public void detachFragment(Fragment fragment, int transition, int transitionStyle) {
1116        if (DEBUG) Log.v(TAG, "detach: " + fragment);
1117        if (!fragment.mDetached) {
1118            fragment.mDetached = true;
1119            if (fragment.mAdded) {
1120                // We are not already in back stack, so need to remove the fragment.
1121                mAdded.remove(fragment);
1122                if (fragment.mHasMenu) {
1123                    mNeedMenuInvalidate = true;
1124                }
1125                fragment.mAdded = false;
1126                fragment.mRemoving = true;
1127                moveToState(fragment, Fragment.CREATED, transition, transitionStyle);
1128            }
1129        }
1130    }
1131
1132    public void attachFragment(Fragment fragment, int transition, int transitionStyle) {
1133        if (DEBUG) Log.v(TAG, "attach: " + fragment);
1134        if (fragment.mDetached) {
1135            fragment.mDetached = false;
1136            if (!fragment.mAdded) {
1137                mAdded.add(fragment);
1138                fragment.mAdded = true;
1139                fragment.mRemoving = false;
1140                if (fragment.mHasMenu) {
1141                    mNeedMenuInvalidate = true;
1142                }
1143                moveToState(fragment, mCurState, transition, transitionStyle);
1144            }
1145        }
1146    }
1147
1148    public Fragment findFragmentById(int id) {
1149        if (mActive != null) {
1150            // First look through added fragments.
1151            for (int i=mAdded.size()-1; i>=0; i--) {
1152                Fragment f = mAdded.get(i);
1153                if (f != null && f.mFragmentId == id) {
1154                    return f;
1155                }
1156            }
1157            // Now for any known fragment.
1158            for (int i=mActive.size()-1; i>=0; i--) {
1159                Fragment f = mActive.get(i);
1160                if (f != null && f.mFragmentId == id) {
1161                    return f;
1162                }
1163            }
1164        }
1165        return null;
1166    }
1167
1168    public Fragment findFragmentByTag(String tag) {
1169        if (mActive != null && tag != null) {
1170            // First look through added fragments.
1171            for (int i=mAdded.size()-1; i>=0; i--) {
1172                Fragment f = mAdded.get(i);
1173                if (f != null && tag.equals(f.mTag)) {
1174                    return f;
1175                }
1176            }
1177            // Now for any known fragment.
1178            for (int i=mActive.size()-1; i>=0; i--) {
1179                Fragment f = mActive.get(i);
1180                if (f != null && tag.equals(f.mTag)) {
1181                    return f;
1182                }
1183            }
1184        }
1185        return null;
1186    }
1187
1188    public Fragment findFragmentByWho(String who) {
1189        if (mActive != null && who != null) {
1190            for (int i=mActive.size()-1; i>=0; i--) {
1191                Fragment f = mActive.get(i);
1192                if (f != null && who.equals(f.mWho)) {
1193                    return f;
1194                }
1195            }
1196        }
1197        return null;
1198    }
1199
1200    private void checkStateLoss() {
1201        if (mStateSaved) {
1202            throw new IllegalStateException(
1203                    "Can not perform this action after onSaveInstanceState");
1204        }
1205        if (mNoTransactionsBecause != null) {
1206            throw new IllegalStateException(
1207                    "Can not perform this action inside of " + mNoTransactionsBecause);
1208        }
1209    }
1210
1211    public void enqueueAction(Runnable action, boolean allowStateLoss) {
1212        if (!allowStateLoss) {
1213            checkStateLoss();
1214        }
1215        synchronized (this) {
1216            if (mActivity == null) {
1217                throw new IllegalStateException("Activity has been destroyed");
1218            }
1219            if (mPendingActions == null) {
1220                mPendingActions = new ArrayList<Runnable>();
1221            }
1222            mPendingActions.add(action);
1223            if (mPendingActions.size() == 1) {
1224                mActivity.mHandler.removeCallbacks(mExecCommit);
1225                mActivity.mHandler.post(mExecCommit);
1226            }
1227        }
1228    }
1229
1230    public int allocBackStackIndex(BackStackRecord bse) {
1231        synchronized (this) {
1232            if (mAvailBackStackIndices == null || mAvailBackStackIndices.size() <= 0) {
1233                if (mBackStackIndices == null) {
1234                    mBackStackIndices = new ArrayList<BackStackRecord>();
1235                }
1236                int index = mBackStackIndices.size();
1237                if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse);
1238                mBackStackIndices.add(bse);
1239                return index;
1240
1241            } else {
1242                int index = mAvailBackStackIndices.remove(mAvailBackStackIndices.size()-1);
1243                if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse);
1244                mBackStackIndices.set(index, bse);
1245                return index;
1246            }
1247        }
1248    }
1249
1250    public void setBackStackIndex(int index, BackStackRecord bse) {
1251        synchronized (this) {
1252            if (mBackStackIndices == null) {
1253                mBackStackIndices = new ArrayList<BackStackRecord>();
1254            }
1255            int N = mBackStackIndices.size();
1256            if (index < N) {
1257                if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse);
1258                mBackStackIndices.set(index, bse);
1259            } else {
1260                while (N < index) {
1261                    mBackStackIndices.add(null);
1262                    if (mAvailBackStackIndices == null) {
1263                        mAvailBackStackIndices = new ArrayList<Integer>();
1264                    }
1265                    if (DEBUG) Log.v(TAG, "Adding available back stack index " + N);
1266                    mAvailBackStackIndices.add(N);
1267                    N++;
1268                }
1269                if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse);
1270                mBackStackIndices.add(bse);
1271            }
1272        }
1273    }
1274
1275    public void freeBackStackIndex(int index) {
1276        synchronized (this) {
1277            mBackStackIndices.set(index, null);
1278            if (mAvailBackStackIndices == null) {
1279                mAvailBackStackIndices = new ArrayList<Integer>();
1280            }
1281            if (DEBUG) Log.v(TAG, "Freeing back stack index " + index);
1282            mAvailBackStackIndices.add(index);
1283        }
1284    }
1285
1286    /**
1287     * Only call from main thread!
1288     */
1289    public boolean execPendingActions() {
1290        if (mExecutingActions) {
1291            throw new IllegalStateException("Recursive entry to executePendingTransactions");
1292        }
1293
1294        if (Looper.myLooper() != mActivity.mHandler.getLooper()) {
1295            throw new IllegalStateException("Must be called from main thread of process");
1296        }
1297
1298        boolean didSomething = false;
1299
1300        while (true) {
1301            int numActions;
1302
1303            synchronized (this) {
1304                if (mPendingActions == null || mPendingActions.size() == 0) {
1305                    return didSomething;
1306                }
1307
1308                numActions = mPendingActions.size();
1309                if (mTmpActions == null || mTmpActions.length < numActions) {
1310                    mTmpActions = new Runnable[numActions];
1311                }
1312                mPendingActions.toArray(mTmpActions);
1313                mPendingActions.clear();
1314                mActivity.mHandler.removeCallbacks(mExecCommit);
1315            }
1316
1317            mExecutingActions = true;
1318            for (int i=0; i<numActions; i++) {
1319                mTmpActions[i].run();
1320            }
1321            mExecutingActions = false;
1322            didSomething = true;
1323        }
1324    }
1325
1326    void reportBackStackChanged() {
1327        if (mBackStackChangeListeners != null) {
1328            for (int i=0; i<mBackStackChangeListeners.size(); i++) {
1329                mBackStackChangeListeners.get(i).onBackStackChanged();
1330            }
1331        }
1332    }
1333
1334    void addBackStackState(BackStackRecord state) {
1335        if (mBackStack == null) {
1336            mBackStack = new ArrayList<BackStackRecord>();
1337        }
1338        mBackStack.add(state);
1339        reportBackStackChanged();
1340    }
1341
1342    boolean popBackStackState(Handler handler, String name, int id, int flags) {
1343        if (mBackStack == null) {
1344            return false;
1345        }
1346        if (name == null && id < 0 && (flags&POP_BACK_STACK_INCLUSIVE) == 0) {
1347            int last = mBackStack.size()-1;
1348            if (last < 0) {
1349                return false;
1350            }
1351            final BackStackRecord bss = mBackStack.remove(last);
1352            bss.popFromBackStack(true);
1353            reportBackStackChanged();
1354        } else {
1355            int index = -1;
1356            if (name != null || id >= 0) {
1357                // If a name or ID is specified, look for that place in
1358                // the stack.
1359                index = mBackStack.size()-1;
1360                while (index >= 0) {
1361                    BackStackRecord bss = mBackStack.get(index);
1362                    if (name != null && name.equals(bss.getName())) {
1363                        break;
1364                    }
1365                    if (id >= 0 && id == bss.mIndex) {
1366                        break;
1367                    }
1368                    index--;
1369                }
1370                if (index < 0) {
1371                    return false;
1372                }
1373                if ((flags&POP_BACK_STACK_INCLUSIVE) != 0) {
1374                    index--;
1375                    // Consume all following entries that match.
1376                    while (index >= 0) {
1377                        BackStackRecord bss = mBackStack.get(index);
1378                        if ((name != null && name.equals(bss.getName()))
1379                                || (id >= 0 && id == bss.mIndex)) {
1380                            index--;
1381                            continue;
1382                        }
1383                        break;
1384                    }
1385                }
1386            }
1387            if (index == mBackStack.size()-1) {
1388                return false;
1389            }
1390            final ArrayList<BackStackRecord> states
1391                    = new ArrayList<BackStackRecord>();
1392            for (int i=mBackStack.size()-1; i>index; i--) {
1393                states.add(mBackStack.remove(i));
1394            }
1395            final int LAST = states.size()-1;
1396            for (int i=0; i<=LAST; i++) {
1397                if (DEBUG) Log.v(TAG, "Popping back stack state: " + states.get(i));
1398                states.get(i).popFromBackStack(i == LAST);
1399            }
1400            reportBackStackChanged();
1401        }
1402        return true;
1403    }
1404
1405    ArrayList<Fragment> retainNonConfig() {
1406        ArrayList<Fragment> fragments = null;
1407        if (mActive != null) {
1408            for (int i=0; i<mActive.size(); i++) {
1409                Fragment f = mActive.get(i);
1410                if (f != null && f.mRetainInstance) {
1411                    if (fragments == null) {
1412                        fragments = new ArrayList<Fragment>();
1413                    }
1414                    fragments.add(f);
1415                    f.mRetaining = true;
1416                }
1417            }
1418        }
1419        return fragments;
1420    }
1421
1422    void saveFragmentViewState(Fragment f) {
1423        if (f.mInnerView == null) {
1424            return;
1425        }
1426        if (mStateArray == null) {
1427            mStateArray = new SparseArray<Parcelable>();
1428        } else {
1429            mStateArray.clear();
1430        }
1431        f.mInnerView.saveHierarchyState(mStateArray);
1432        if (mStateArray.size() > 0) {
1433            f.mSavedViewState = mStateArray;
1434            mStateArray = null;
1435        }
1436    }
1437
1438    Parcelable saveAllState() {
1439        // Make sure all pending operations have now been executed to get
1440        // our state update-to-date.
1441        execPendingActions();
1442
1443        if (HONEYCOMB) {
1444            // As of Honeycomb, we save state after pausing.  Prior to that
1445            // it is before pausing.  With fragments this is an issue, since
1446            // there are many things you may do after pausing but before
1447            // stopping that change the fragment state.  For those older
1448            // devices, we will not at this point say that we have saved
1449            // the state, so we will allow them to continue doing fragment
1450            // transactions.  This retains the same semantics as Honeycomb,
1451            // though you do have the risk of losing the very most recent state
1452            // if the process is killed...  we'll live with that.
1453            mStateSaved = true;
1454        }
1455
1456        if (mActive == null || mActive.size() <= 0) {
1457            return null;
1458        }
1459
1460        // First collect all active fragments.
1461        int N = mActive.size();
1462        FragmentState[] active = new FragmentState[N];
1463        boolean haveFragments = false;
1464        for (int i=0; i<N; i++) {
1465            Fragment f = mActive.get(i);
1466            if (f != null) {
1467                haveFragments = true;
1468
1469                FragmentState fs = new FragmentState(f);
1470                active[i] = fs;
1471
1472                if (f.mState > Fragment.INITIALIZING && fs.mSavedFragmentState == null) {
1473                    if (mStateBundle == null) {
1474                        mStateBundle = new Bundle();
1475                    }
1476                    f.onSaveInstanceState(mStateBundle);
1477                    if (!mStateBundle.isEmpty()) {
1478                        fs.mSavedFragmentState = mStateBundle;
1479                        mStateBundle = null;
1480                    }
1481
1482                    if (f.mView != null) {
1483                        saveFragmentViewState(f);
1484                        if (f.mSavedViewState != null) {
1485                            if (fs.mSavedFragmentState == null) {
1486                                fs.mSavedFragmentState = new Bundle();
1487                            }
1488                            fs.mSavedFragmentState.putSparseParcelableArray(
1489                                    FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState);
1490                        }
1491                    }
1492
1493                    if (f.mTarget != null) {
1494                        if (f.mTarget.mIndex < 0) {
1495                            String msg = "Failure saving state: " + f
1496                                + " has target not in fragment manager: " + f.mTarget;
1497                            Log.e(TAG, msg);
1498                            dump("  ", null, new PrintWriter(new LogWriter(TAG)), new String[] { });
1499                            throw new IllegalStateException(msg);
1500                        }
1501                        if (fs.mSavedFragmentState == null) {
1502                            fs.mSavedFragmentState = new Bundle();
1503                        }
1504                        putFragment(fs.mSavedFragmentState,
1505                                FragmentManagerImpl.TARGET_STATE_TAG, f.mTarget);
1506                        if (f.mTargetRequestCode != 0) {
1507                            fs.mSavedFragmentState.putInt(
1508                                    FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG,
1509                                    f.mTargetRequestCode);
1510                        }
1511                    }
1512
1513                } else {
1514                    fs.mSavedFragmentState = f.mSavedFragmentState;
1515                }
1516
1517                if (DEBUG) Log.v(TAG, "Saved state of " + f + ": "
1518                        + fs.mSavedFragmentState);
1519            }
1520        }
1521
1522        if (!haveFragments) {
1523            if (DEBUG) Log.v(TAG, "saveAllState: no fragments!");
1524            return null;
1525        }
1526
1527        int[] added = null;
1528        BackStackState[] backStack = null;
1529
1530        // Build list of currently added fragments.
1531        if (mAdded != null) {
1532            N = mAdded.size();
1533            if (N > 0) {
1534                added = new int[N];
1535                for (int i=0; i<N; i++) {
1536                    added[i] = mAdded.get(i).mIndex;
1537                    if (DEBUG) Log.v(TAG, "saveAllState: adding fragment #" + i
1538                            + ": " + mAdded.get(i));
1539                }
1540            }
1541        }
1542
1543        // Now save back stack.
1544        if (mBackStack != null) {
1545            N = mBackStack.size();
1546            if (N > 0) {
1547                backStack = new BackStackState[N];
1548                for (int i=0; i<N; i++) {
1549                    backStack[i] = new BackStackState(this, mBackStack.get(i));
1550                    if (DEBUG) Log.v(TAG, "saveAllState: adding back stack #" + i
1551                            + ": " + mBackStack.get(i));
1552                }
1553            }
1554        }
1555
1556        FragmentManagerState fms = new FragmentManagerState();
1557        fms.mActive = active;
1558        fms.mAdded = added;
1559        fms.mBackStack = backStack;
1560        return fms;
1561    }
1562
1563    void restoreAllState(Parcelable state, ArrayList<Fragment> nonConfig) {
1564        // If there is no saved state at all, then there can not be
1565        // any nonConfig fragments either, so that is that.
1566        if (state == null) return;
1567        FragmentManagerState fms = (FragmentManagerState)state;
1568        if (fms.mActive == null) return;
1569
1570        // First re-attach any non-config instances we are retaining back
1571        // to their saved state, so we don't try to instantiate them again.
1572        if (nonConfig != null) {
1573            for (int i=0; i<nonConfig.size(); i++) {
1574                Fragment f = nonConfig.get(i);
1575                if (DEBUG) Log.v(TAG, "restoreAllState: re-attaching retained " + f);
1576                FragmentState fs = fms.mActive[f.mIndex];
1577                fs.mInstance = f;
1578                f.mSavedViewState = null;
1579                f.mBackStackNesting = 0;
1580                f.mInLayout = false;
1581                f.mAdded = false;
1582                if (fs.mSavedFragmentState != null) {
1583                    fs.mSavedFragmentState.setClassLoader(mActivity.getClassLoader());
1584                    f.mSavedViewState = fs.mSavedFragmentState.getSparseParcelableArray(
1585                            FragmentManagerImpl.VIEW_STATE_TAG);
1586                }
1587            }
1588        }
1589
1590        // Build the full list of active fragments, instantiating them from
1591        // their saved state.
1592        mActive = new ArrayList<Fragment>(fms.mActive.length);
1593        if (mAvailIndices != null) {
1594            mAvailIndices.clear();
1595        }
1596        for (int i=0; i<fms.mActive.length; i++) {
1597            FragmentState fs = fms.mActive[i];
1598            if (fs != null) {
1599                Fragment f = fs.instantiate(mActivity);
1600                if (DEBUG) Log.v(TAG, "restoreAllState: adding #" + i + ": " + f);
1601                mActive.add(f);
1602                // Now that the fragment is instantiated (or came from being
1603                // retained above), clear mInstance in case we end up re-restoring
1604                // from this FragmentState again.
1605                fs.mInstance = null;
1606            } else {
1607                if (DEBUG) Log.v(TAG, "restoreAllState: adding #" + i + ": (null)");
1608                mActive.add(null);
1609                if (mAvailIndices == null) {
1610                    mAvailIndices = new ArrayList<Integer>();
1611                }
1612                if (DEBUG) Log.v(TAG, "restoreAllState: adding avail #" + i);
1613                mAvailIndices.add(i);
1614            }
1615        }
1616
1617        // Update the target of all retained fragments.
1618        if (nonConfig != null) {
1619            for (int i=0; i<nonConfig.size(); i++) {
1620                Fragment f = nonConfig.get(i);
1621                if (f.mTarget != null) {
1622                    if (f.mTarget.mIndex < mActive.size()) {
1623                        f.mTarget = mActive.get(f.mTarget.mIndex);
1624                    } else {
1625                        Log.w(TAG, "Re-attaching retained fragment " + f
1626                                + " target no longer exists: " + f.mTarget);
1627                        f.mTarget = null;
1628                    }
1629                }
1630            }
1631        }
1632
1633        // Build the list of currently added fragments.
1634        if (fms.mAdded != null) {
1635            mAdded = new ArrayList<Fragment>(fms.mAdded.length);
1636            for (int i=0; i<fms.mAdded.length; i++) {
1637                Fragment f = mActive.get(fms.mAdded[i]);
1638                if (f == null) {
1639                    throw new IllegalStateException(
1640                            "No instantiated fragment for index #" + fms.mAdded[i]);
1641                }
1642                f.mAdded = true;
1643                f.mImmediateActivity = mActivity;
1644                if (DEBUG) Log.v(TAG, "restoreAllState: making added #" + i + ": " + f);
1645                mAdded.add(f);
1646            }
1647        } else {
1648            mAdded = null;
1649        }
1650
1651        // Build the back stack.
1652        if (fms.mBackStack != null) {
1653            mBackStack = new ArrayList<BackStackRecord>(fms.mBackStack.length);
1654            for (int i=0; i<fms.mBackStack.length; i++) {
1655                BackStackRecord bse = fms.mBackStack[i].instantiate(this);
1656                if (DEBUG) Log.v(TAG, "restoreAllState: adding bse #" + i
1657                        + " (index " + bse.mIndex + "): " + bse);
1658                mBackStack.add(bse);
1659                if (bse.mIndex >= 0) {
1660                    setBackStackIndex(bse.mIndex, bse);
1661                }
1662            }
1663        } else {
1664            mBackStack = null;
1665        }
1666    }
1667
1668    public void attachActivity(FragmentActivity activity) {
1669        if (mActivity != null) throw new IllegalStateException();
1670        mActivity = activity;
1671    }
1672
1673    public void noteStateNotSaved() {
1674        mStateSaved = false;
1675    }
1676
1677    public void dispatchCreate() {
1678        mStateSaved = false;
1679        moveToState(Fragment.CREATED, false);
1680    }
1681
1682    public void dispatchActivityCreated() {
1683        mStateSaved = false;
1684        moveToState(Fragment.ACTIVITY_CREATED, false);
1685    }
1686
1687    public void dispatchStart() {
1688        mStateSaved = false;
1689        moveToState(Fragment.STARTED, false);
1690    }
1691
1692    public void dispatchResume() {
1693        mStateSaved = false;
1694        moveToState(Fragment.RESUMED, false);
1695    }
1696
1697    public void dispatchPause() {
1698        moveToState(Fragment.STARTED, false);
1699    }
1700
1701    public void dispatchStop() {
1702        // See saveAllState() for the explanation of this.  We do this for
1703        // all platform versions, to keep our behavior more consistent between
1704        // them.
1705        mStateSaved = true;
1706
1707        moveToState(Fragment.STOPPED, false);
1708    }
1709
1710    public void dispatchReallyStop(boolean retaining) {
1711        if (mActive != null) {
1712            for (int i=0; i<mAdded.size(); i++) {
1713                Fragment f = mAdded.get(i);
1714                if (f != null) {
1715                    f.performReallyStop(retaining);
1716                }
1717            }
1718        }
1719    }
1720
1721    public void dispatchDestroy() {
1722        mDestroyed = true;
1723        moveToState(Fragment.INITIALIZING, false);
1724        mActivity = null;
1725    }
1726
1727    public void dispatchConfigurationChanged(Configuration newConfig) {
1728        if (mActive != null) {
1729            for (int i=0; i<mAdded.size(); i++) {
1730                Fragment f = mAdded.get(i);
1731                if (f != null) {
1732                    f.onConfigurationChanged(newConfig);
1733                }
1734            }
1735        }
1736    }
1737
1738    public void dispatchLowMemory() {
1739        if (mActive != null) {
1740            for (int i=0; i<mAdded.size(); i++) {
1741                Fragment f = mAdded.get(i);
1742                if (f != null) {
1743                    f.onLowMemory();
1744                }
1745            }
1746        }
1747    }
1748
1749    public boolean dispatchCreateOptionsMenu(Menu menu, MenuInflater inflater) {
1750        boolean show = false;
1751        ArrayList<Fragment> newMenus = null;
1752        if (mActive != null) {
1753            for (int i=0; i<mAdded.size(); i++) {
1754                Fragment f = mAdded.get(i);
1755                if (f != null && !f.mHidden && f.mHasMenu) {
1756                    show = true;
1757                    f.onCreateOptionsMenu(menu, inflater);
1758                    if (newMenus == null) {
1759                        newMenus = new ArrayList<Fragment>();
1760                    }
1761                    newMenus.add(f);
1762                }
1763            }
1764        }
1765
1766        if (mCreatedMenus != null) {
1767            for (int i=0; i<mCreatedMenus.size(); i++) {
1768                Fragment f = mCreatedMenus.get(i);
1769                if (newMenus == null || !newMenus.contains(f)) {
1770                    f.onDestroyOptionsMenu();
1771                }
1772            }
1773        }
1774
1775        mCreatedMenus = newMenus;
1776
1777        return show;
1778    }
1779
1780    public boolean dispatchPrepareOptionsMenu(Menu menu) {
1781        boolean show = false;
1782        if (mActive != null) {
1783            for (int i=0; i<mAdded.size(); i++) {
1784                Fragment f = mAdded.get(i);
1785                if (f != null && !f.mHidden && f.mHasMenu) {
1786                    show = true;
1787                    f.onPrepareOptionsMenu(menu);
1788                }
1789            }
1790        }
1791        return show;
1792    }
1793
1794    public boolean dispatchOptionsItemSelected(MenuItem item) {
1795        if (mActive != null) {
1796            for (int i=0; i<mAdded.size(); i++) {
1797                Fragment f = mAdded.get(i);
1798                if (f != null && !f.mHidden && f.mHasMenu) {
1799                    if (f.onOptionsItemSelected(item)) {
1800                        return true;
1801                    }
1802                }
1803            }
1804        }
1805        return false;
1806    }
1807
1808    public boolean dispatchContextItemSelected(MenuItem item) {
1809        if (mActive != null) {
1810            for (int i=0; i<mAdded.size(); i++) {
1811                Fragment f = mAdded.get(i);
1812                if (f != null && !f.mHidden) {
1813                    if (f.onContextItemSelected(item)) {
1814                        return true;
1815                    }
1816                }
1817            }
1818        }
1819        return false;
1820    }
1821
1822    public void dispatchOptionsMenuClosed(Menu menu) {
1823        if (mActive != null) {
1824            for (int i=0; i<mAdded.size(); i++) {
1825                Fragment f = mAdded.get(i);
1826                if (f != null && !f.mHidden && f.mHasMenu) {
1827                    f.onOptionsMenuClosed(menu);
1828                }
1829            }
1830        }
1831    }
1832
1833    public static int reverseTransit(int transit) {
1834        int rev = 0;
1835        switch (transit) {
1836            case FragmentTransaction.TRANSIT_FRAGMENT_OPEN:
1837                rev = FragmentTransaction.TRANSIT_FRAGMENT_CLOSE;
1838                break;
1839            case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE:
1840                rev = FragmentTransaction.TRANSIT_FRAGMENT_OPEN;
1841                break;
1842            case FragmentTransaction.TRANSIT_FRAGMENT_FADE:
1843                rev = FragmentTransaction.TRANSIT_FRAGMENT_FADE;
1844                break;
1845        }
1846        return rev;
1847
1848    }
1849
1850    public static final int ANIM_STYLE_OPEN_ENTER = 1;
1851    public static final int ANIM_STYLE_OPEN_EXIT = 2;
1852    public static final int ANIM_STYLE_CLOSE_ENTER = 3;
1853    public static final int ANIM_STYLE_CLOSE_EXIT = 4;
1854    public static final int ANIM_STYLE_FADE_ENTER = 5;
1855    public static final int ANIM_STYLE_FADE_EXIT = 6;
1856
1857    public static int transitToStyleIndex(int transit, boolean enter) {
1858        int animAttr = -1;
1859        switch (transit) {
1860            case FragmentTransaction.TRANSIT_FRAGMENT_OPEN:
1861                animAttr = enter ? ANIM_STYLE_OPEN_ENTER : ANIM_STYLE_OPEN_EXIT;
1862                break;
1863            case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE:
1864                animAttr = enter ? ANIM_STYLE_CLOSE_ENTER : ANIM_STYLE_CLOSE_EXIT;
1865                break;
1866            case FragmentTransaction.TRANSIT_FRAGMENT_FADE:
1867                animAttr = enter ? ANIM_STYLE_FADE_ENTER : ANIM_STYLE_FADE_EXIT;
1868                break;
1869        }
1870        return animAttr;
1871    }
1872}
1873