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