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