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