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