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