FragmentManager.java revision abc968f1eba800c34a4008deb43b015da5d23a5f
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        for (int i=0; i<mActive.size(); i++) {
1085            Fragment f = mActive.get(i);
1086            if (f != null) {
1087                performPendingDeferredStart(f);
1088            }
1089        }
1090    }
1091
1092    void makeActive(Fragment f) {
1093        if (f.mIndex >= 0) {
1094            return;
1095        }
1096
1097        if (mAvailIndices == null || mAvailIndices.size() <= 0) {
1098            if (mActive == null) {
1099                mActive = new ArrayList<Fragment>();
1100            }
1101            f.setIndex(mActive.size());
1102            mActive.add(f);
1103
1104        } else {
1105            f.setIndex(mAvailIndices.remove(mAvailIndices.size()-1));
1106            mActive.set(f.mIndex, f);
1107        }
1108    }
1109
1110    void makeInactive(Fragment f) {
1111        if (f.mIndex < 0) {
1112            return;
1113        }
1114
1115        if (DEBUG) Log.v(TAG, "Freeing fragment index " + f.mIndex);
1116        mActive.set(f.mIndex, null);
1117        if (mAvailIndices == null) {
1118            mAvailIndices = new ArrayList<Integer>();
1119        }
1120        mAvailIndices.add(f.mIndex);
1121        mActivity.invalidateSupportFragmentIndex(f.mIndex);
1122        f.initState();
1123    }
1124
1125    public void addFragment(Fragment fragment, boolean moveToStateNow) {
1126        if (mAdded == null) {
1127            mAdded = new ArrayList<Fragment>();
1128        }
1129        if (DEBUG) Log.v(TAG, "add: " + fragment);
1130        makeActive(fragment);
1131        if (!fragment.mDetached) {
1132            mAdded.add(fragment);
1133            fragment.mAdded = true;
1134            fragment.mRemoving = false;
1135            if (fragment.mHasMenu && fragment.mMenuVisible) {
1136                mNeedMenuInvalidate = true;
1137            }
1138            if (moveToStateNow) {
1139                moveToState(fragment);
1140            }
1141        }
1142    }
1143
1144    public void removeFragment(Fragment fragment, int transition, int transitionStyle) {
1145        if (DEBUG) Log.v(TAG, "remove: " + fragment + " nesting=" + fragment.mBackStackNesting);
1146        final boolean inactive = !fragment.isInBackStack();
1147        if (!fragment.mDetached || inactive) {
1148            mAdded.remove(fragment);
1149            if (fragment.mHasMenu && fragment.mMenuVisible) {
1150                mNeedMenuInvalidate = true;
1151            }
1152            fragment.mAdded = false;
1153            fragment.mRemoving = true;
1154            moveToState(fragment, inactive ? Fragment.INITIALIZING : Fragment.CREATED,
1155                    transition, transitionStyle);
1156        }
1157    }
1158
1159    public void hideFragment(Fragment fragment, int transition, int transitionStyle) {
1160        if (DEBUG) Log.v(TAG, "hide: " + fragment);
1161        if (!fragment.mHidden) {
1162            fragment.mHidden = true;
1163            if (fragment.mView != null) {
1164                Animation anim = loadAnimation(fragment, transition, true,
1165                        transitionStyle);
1166                if (anim != null) {
1167                    fragment.mView.startAnimation(anim);
1168                }
1169                fragment.mView.setVisibility(View.GONE);
1170            }
1171            if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) {
1172                mNeedMenuInvalidate = true;
1173            }
1174            fragment.onHiddenChanged(true);
1175        }
1176    }
1177
1178    public void showFragment(Fragment fragment, int transition, int transitionStyle) {
1179        if (DEBUG) Log.v(TAG, "show: " + fragment);
1180        if (fragment.mHidden) {
1181            fragment.mHidden = false;
1182            if (fragment.mView != null) {
1183                Animation anim = loadAnimation(fragment, transition, true,
1184                        transitionStyle);
1185                if (anim != null) {
1186                    fragment.mView.startAnimation(anim);
1187                }
1188                fragment.mView.setVisibility(View.VISIBLE);
1189            }
1190            if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) {
1191                mNeedMenuInvalidate = true;
1192            }
1193            fragment.onHiddenChanged(false);
1194        }
1195    }
1196
1197    public void detachFragment(Fragment fragment, int transition, int transitionStyle) {
1198        if (DEBUG) Log.v(TAG, "detach: " + fragment);
1199        if (!fragment.mDetached) {
1200            fragment.mDetached = true;
1201            if (fragment.mAdded) {
1202                // We are not already in back stack, so need to remove the fragment.
1203                mAdded.remove(fragment);
1204                if (fragment.mHasMenu && fragment.mMenuVisible) {
1205                    mNeedMenuInvalidate = true;
1206                }
1207                fragment.mAdded = false;
1208                moveToState(fragment, Fragment.CREATED, transition, transitionStyle);
1209            }
1210        }
1211    }
1212
1213    public void attachFragment(Fragment fragment, int transition, int transitionStyle) {
1214        if (DEBUG) Log.v(TAG, "attach: " + fragment);
1215        if (fragment.mDetached) {
1216            fragment.mDetached = false;
1217            if (!fragment.mAdded) {
1218                mAdded.add(fragment);
1219                fragment.mAdded = true;
1220                if (fragment.mHasMenu && fragment.mMenuVisible) {
1221                    mNeedMenuInvalidate = true;
1222                }
1223                moveToState(fragment, mCurState, transition, transitionStyle);
1224            }
1225        }
1226    }
1227
1228    public Fragment findFragmentById(int id) {
1229        if (mActive != null) {
1230            // First look through added fragments.
1231            for (int i=mAdded.size()-1; i>=0; i--) {
1232                Fragment f = mAdded.get(i);
1233                if (f != null && f.mFragmentId == id) {
1234                    return f;
1235                }
1236            }
1237            // Now for any known fragment.
1238            for (int i=mActive.size()-1; i>=0; i--) {
1239                Fragment f = mActive.get(i);
1240                if (f != null && f.mFragmentId == id) {
1241                    return f;
1242                }
1243            }
1244        }
1245        return null;
1246    }
1247
1248    public Fragment findFragmentByTag(String tag) {
1249        if (mActive != null && tag != null) {
1250            // First look through added fragments.
1251            for (int i=mAdded.size()-1; i>=0; i--) {
1252                Fragment f = mAdded.get(i);
1253                if (f != null && tag.equals(f.mTag)) {
1254                    return f;
1255                }
1256            }
1257            // Now for any known fragment.
1258            for (int i=mActive.size()-1; i>=0; i--) {
1259                Fragment f = mActive.get(i);
1260                if (f != null && tag.equals(f.mTag)) {
1261                    return f;
1262                }
1263            }
1264        }
1265        return null;
1266    }
1267
1268    public Fragment findFragmentByWho(String who) {
1269        if (mActive != null && who != null) {
1270            for (int i=mActive.size()-1; i>=0; i--) {
1271                Fragment f = mActive.get(i);
1272                if (f != null && who.equals(f.mWho)) {
1273                    return f;
1274                }
1275            }
1276        }
1277        return null;
1278    }
1279
1280    private void checkStateLoss() {
1281        if (mStateSaved) {
1282            throw new IllegalStateException(
1283                    "Can not perform this action after onSaveInstanceState");
1284        }
1285        if (mNoTransactionsBecause != null) {
1286            throw new IllegalStateException(
1287                    "Can not perform this action inside of " + mNoTransactionsBecause);
1288        }
1289    }
1290
1291    public void enqueueAction(Runnable action, boolean allowStateLoss) {
1292        if (!allowStateLoss) {
1293            checkStateLoss();
1294        }
1295        synchronized (this) {
1296            if (mActivity == null) {
1297                throw new IllegalStateException("Activity has been destroyed");
1298            }
1299            if (mPendingActions == null) {
1300                mPendingActions = new ArrayList<Runnable>();
1301            }
1302            mPendingActions.add(action);
1303            if (mPendingActions.size() == 1) {
1304                mActivity.mHandler.removeCallbacks(mExecCommit);
1305                mActivity.mHandler.post(mExecCommit);
1306            }
1307        }
1308    }
1309
1310    public int allocBackStackIndex(BackStackRecord bse) {
1311        synchronized (this) {
1312            if (mAvailBackStackIndices == null || mAvailBackStackIndices.size() <= 0) {
1313                if (mBackStackIndices == null) {
1314                    mBackStackIndices = new ArrayList<BackStackRecord>();
1315                }
1316                int index = mBackStackIndices.size();
1317                if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse);
1318                mBackStackIndices.add(bse);
1319                return index;
1320
1321            } else {
1322                int index = mAvailBackStackIndices.remove(mAvailBackStackIndices.size()-1);
1323                if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse);
1324                mBackStackIndices.set(index, bse);
1325                return index;
1326            }
1327        }
1328    }
1329
1330    public void setBackStackIndex(int index, BackStackRecord bse) {
1331        synchronized (this) {
1332            if (mBackStackIndices == null) {
1333                mBackStackIndices = new ArrayList<BackStackRecord>();
1334            }
1335            int N = mBackStackIndices.size();
1336            if (index < N) {
1337                if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse);
1338                mBackStackIndices.set(index, bse);
1339            } else {
1340                while (N < index) {
1341                    mBackStackIndices.add(null);
1342                    if (mAvailBackStackIndices == null) {
1343                        mAvailBackStackIndices = new ArrayList<Integer>();
1344                    }
1345                    if (DEBUG) Log.v(TAG, "Adding available back stack index " + N);
1346                    mAvailBackStackIndices.add(N);
1347                    N++;
1348                }
1349                if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse);
1350                mBackStackIndices.add(bse);
1351            }
1352        }
1353    }
1354
1355    public void freeBackStackIndex(int index) {
1356        synchronized (this) {
1357            mBackStackIndices.set(index, null);
1358            if (mAvailBackStackIndices == null) {
1359                mAvailBackStackIndices = new ArrayList<Integer>();
1360            }
1361            if (DEBUG) Log.v(TAG, "Freeing back stack index " + index);
1362            mAvailBackStackIndices.add(index);
1363        }
1364    }
1365
1366    /**
1367     * Only call from main thread!
1368     */
1369    public boolean execPendingActions() {
1370        if (mExecutingActions) {
1371            throw new IllegalStateException("Recursive entry to executePendingTransactions");
1372        }
1373
1374        if (Looper.myLooper() != mActivity.mHandler.getLooper()) {
1375            throw new IllegalStateException("Must be called from main thread of process");
1376        }
1377
1378        boolean didSomething = false;
1379
1380        while (true) {
1381            int numActions;
1382
1383            synchronized (this) {
1384                if (mPendingActions == null || mPendingActions.size() == 0) {
1385                    return didSomething;
1386                }
1387
1388                numActions = mPendingActions.size();
1389                if (mTmpActions == null || mTmpActions.length < numActions) {
1390                    mTmpActions = new Runnable[numActions];
1391                }
1392                mPendingActions.toArray(mTmpActions);
1393                mPendingActions.clear();
1394                mActivity.mHandler.removeCallbacks(mExecCommit);
1395            }
1396
1397            mExecutingActions = true;
1398            for (int i=0; i<numActions; i++) {
1399                mTmpActions[i].run();
1400                mTmpActions[i] = null;
1401            }
1402            mExecutingActions = false;
1403            didSomething = true;
1404        }
1405    }
1406
1407    void reportBackStackChanged() {
1408        if (mBackStackChangeListeners != null) {
1409            for (int i=0; i<mBackStackChangeListeners.size(); i++) {
1410                mBackStackChangeListeners.get(i).onBackStackChanged();
1411            }
1412        }
1413    }
1414
1415    void addBackStackState(BackStackRecord state) {
1416        if (mBackStack == null) {
1417            mBackStack = new ArrayList<BackStackRecord>();
1418        }
1419        mBackStack.add(state);
1420        reportBackStackChanged();
1421    }
1422
1423    boolean popBackStackState(Handler handler, String name, int id, int flags) {
1424        if (mBackStack == null) {
1425            return false;
1426        }
1427        if (name == null && id < 0 && (flags&POP_BACK_STACK_INCLUSIVE) == 0) {
1428            int last = mBackStack.size()-1;
1429            if (last < 0) {
1430                return false;
1431            }
1432            final BackStackRecord bss = mBackStack.remove(last);
1433            bss.popFromBackStack(true);
1434            reportBackStackChanged();
1435        } else {
1436            int index = -1;
1437            if (name != null || id >= 0) {
1438                // If a name or ID is specified, look for that place in
1439                // the stack.
1440                index = mBackStack.size()-1;
1441                while (index >= 0) {
1442                    BackStackRecord bss = mBackStack.get(index);
1443                    if (name != null && name.equals(bss.getName())) {
1444                        break;
1445                    }
1446                    if (id >= 0 && id == bss.mIndex) {
1447                        break;
1448                    }
1449                    index--;
1450                }
1451                if (index < 0) {
1452                    return false;
1453                }
1454                if ((flags&POP_BACK_STACK_INCLUSIVE) != 0) {
1455                    index--;
1456                    // Consume all following entries that match.
1457                    while (index >= 0) {
1458                        BackStackRecord bss = mBackStack.get(index);
1459                        if ((name != null && name.equals(bss.getName()))
1460                                || (id >= 0 && id == bss.mIndex)) {
1461                            index--;
1462                            continue;
1463                        }
1464                        break;
1465                    }
1466                }
1467            }
1468            if (index == mBackStack.size()-1) {
1469                return false;
1470            }
1471            final ArrayList<BackStackRecord> states
1472                    = new ArrayList<BackStackRecord>();
1473            for (int i=mBackStack.size()-1; i>index; i--) {
1474                states.add(mBackStack.remove(i));
1475            }
1476            final int LAST = states.size()-1;
1477            for (int i=0; i<=LAST; i++) {
1478                if (DEBUG) Log.v(TAG, "Popping back stack state: " + states.get(i));
1479                states.get(i).popFromBackStack(i == LAST);
1480            }
1481            reportBackStackChanged();
1482        }
1483        return true;
1484    }
1485
1486    ArrayList<Fragment> retainNonConfig() {
1487        ArrayList<Fragment> fragments = null;
1488        if (mActive != null) {
1489            for (int i=0; i<mActive.size(); i++) {
1490                Fragment f = mActive.get(i);
1491                if (f != null && f.mRetainInstance) {
1492                    if (fragments == null) {
1493                        fragments = new ArrayList<Fragment>();
1494                    }
1495                    fragments.add(f);
1496                    f.mRetaining = true;
1497                    f.mTargetIndex = f.mTarget != null ? f.mTarget.mIndex : -1;
1498                }
1499            }
1500        }
1501        return fragments;
1502    }
1503
1504    void saveFragmentViewState(Fragment f) {
1505        if (f.mInnerView == null) {
1506            return;
1507        }
1508        if (mStateArray == null) {
1509            mStateArray = new SparseArray<Parcelable>();
1510        } else {
1511            mStateArray.clear();
1512        }
1513        f.mInnerView.saveHierarchyState(mStateArray);
1514        if (mStateArray.size() > 0) {
1515            f.mSavedViewState = mStateArray;
1516            mStateArray = null;
1517        }
1518    }
1519
1520    Bundle saveFragmentBasicState(Fragment f) {
1521        Bundle result = null;
1522
1523        if (mStateBundle == null) {
1524            mStateBundle = new Bundle();
1525        }
1526        f.onSaveInstanceState(mStateBundle);
1527        if (!mStateBundle.isEmpty()) {
1528            result = mStateBundle;
1529            mStateBundle = null;
1530        }
1531
1532        if (f.mView != null) {
1533            saveFragmentViewState(f);
1534        }
1535        if (f.mSavedViewState != null) {
1536            if (result == null) {
1537                result = new Bundle();
1538            }
1539            result.putSparseParcelableArray(
1540                    FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState);
1541        }
1542
1543        return result;
1544    }
1545
1546    Parcelable saveAllState() {
1547        // Make sure all pending operations have now been executed to get
1548        // our state update-to-date.
1549        execPendingActions();
1550
1551        if (HONEYCOMB) {
1552            // As of Honeycomb, we save state after pausing.  Prior to that
1553            // it is before pausing.  With fragments this is an issue, since
1554            // there are many things you may do after pausing but before
1555            // stopping that change the fragment state.  For those older
1556            // devices, we will not at this point say that we have saved
1557            // the state, so we will allow them to continue doing fragment
1558            // transactions.  This retains the same semantics as Honeycomb,
1559            // though you do have the risk of losing the very most recent state
1560            // if the process is killed...  we'll live with that.
1561            mStateSaved = true;
1562        }
1563
1564        if (mActive == null || mActive.size() <= 0) {
1565            return null;
1566        }
1567
1568        // First collect all active fragments.
1569        int N = mActive.size();
1570        FragmentState[] active = new FragmentState[N];
1571        boolean haveFragments = false;
1572        for (int i=0; i<N; i++) {
1573            Fragment f = mActive.get(i);
1574            if (f != null) {
1575                haveFragments = true;
1576
1577                FragmentState fs = new FragmentState(f);
1578                active[i] = fs;
1579
1580                if (f.mState > Fragment.INITIALIZING && fs.mSavedFragmentState == null) {
1581                    fs.mSavedFragmentState = saveFragmentBasicState(f);
1582
1583                    if (f.mTarget != null) {
1584                        if (f.mTarget.mIndex < 0) {
1585                            String msg = "Failure saving state: " + f
1586                                + " has target not in fragment manager: " + f.mTarget;
1587                            Log.e(TAG, msg);
1588                            dump("  ", null, new PrintWriter(new LogWriter(TAG)), new String[] { });
1589                            throw new IllegalStateException(msg);
1590                        }
1591                        if (fs.mSavedFragmentState == null) {
1592                            fs.mSavedFragmentState = new Bundle();
1593                        }
1594                        putFragment(fs.mSavedFragmentState,
1595                                FragmentManagerImpl.TARGET_STATE_TAG, f.mTarget);
1596                        if (f.mTargetRequestCode != 0) {
1597                            fs.mSavedFragmentState.putInt(
1598                                    FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG,
1599                                    f.mTargetRequestCode);
1600                        }
1601                    }
1602
1603                } else {
1604                    fs.mSavedFragmentState = f.mSavedFragmentState;
1605                }
1606
1607                if (DEBUG) Log.v(TAG, "Saved state of " + f + ": "
1608                        + fs.mSavedFragmentState);
1609            }
1610        }
1611
1612        if (!haveFragments) {
1613            if (DEBUG) Log.v(TAG, "saveAllState: no fragments!");
1614            return null;
1615        }
1616
1617        int[] added = null;
1618        BackStackState[] backStack = null;
1619
1620        // Build list of currently added fragments.
1621        if (mAdded != null) {
1622            N = mAdded.size();
1623            if (N > 0) {
1624                added = new int[N];
1625                for (int i=0; i<N; i++) {
1626                    added[i] = mAdded.get(i).mIndex;
1627                    if (DEBUG) Log.v(TAG, "saveAllState: adding fragment #" + i
1628                            + ": " + mAdded.get(i));
1629                }
1630            }
1631        }
1632
1633        // Now save back stack.
1634        if (mBackStack != null) {
1635            N = mBackStack.size();
1636            if (N > 0) {
1637                backStack = new BackStackState[N];
1638                for (int i=0; i<N; i++) {
1639                    backStack[i] = new BackStackState(this, mBackStack.get(i));
1640                    if (DEBUG) Log.v(TAG, "saveAllState: adding back stack #" + i
1641                            + ": " + mBackStack.get(i));
1642                }
1643            }
1644        }
1645
1646        FragmentManagerState fms = new FragmentManagerState();
1647        fms.mActive = active;
1648        fms.mAdded = added;
1649        fms.mBackStack = backStack;
1650        return fms;
1651    }
1652
1653    void restoreAllState(Parcelable state, ArrayList<Fragment> nonConfig) {
1654        // If there is no saved state at all, then there can not be
1655        // any nonConfig fragments either, so that is that.
1656        if (state == null) return;
1657        FragmentManagerState fms = (FragmentManagerState)state;
1658        if (fms.mActive == null) return;
1659
1660        // First re-attach any non-config instances we are retaining back
1661        // to their saved state, so we don't try to instantiate them again.
1662        if (nonConfig != null) {
1663            for (int i=0; i<nonConfig.size(); i++) {
1664                Fragment f = nonConfig.get(i);
1665                if (DEBUG) Log.v(TAG, "restoreAllState: re-attaching retained " + f);
1666                FragmentState fs = fms.mActive[f.mIndex];
1667                fs.mInstance = f;
1668                f.mSavedViewState = null;
1669                f.mBackStackNesting = 0;
1670                f.mInLayout = false;
1671                f.mAdded = false;
1672                f.mTarget = null;
1673                if (fs.mSavedFragmentState != null) {
1674                    fs.mSavedFragmentState.setClassLoader(mActivity.getClassLoader());
1675                    f.mSavedViewState = fs.mSavedFragmentState.getSparseParcelableArray(
1676                            FragmentManagerImpl.VIEW_STATE_TAG);
1677                }
1678            }
1679        }
1680
1681        // Build the full list of active fragments, instantiating them from
1682        // their saved state.
1683        mActive = new ArrayList<Fragment>(fms.mActive.length);
1684        if (mAvailIndices != null) {
1685            mAvailIndices.clear();
1686        }
1687        for (int i=0; i<fms.mActive.length; i++) {
1688            FragmentState fs = fms.mActive[i];
1689            if (fs != null) {
1690                Fragment f = fs.instantiate(mActivity);
1691                if (DEBUG) Log.v(TAG, "restoreAllState: adding #" + i + ": " + f);
1692                mActive.add(f);
1693                // Now that the fragment is instantiated (or came from being
1694                // retained above), clear mInstance in case we end up re-restoring
1695                // from this FragmentState again.
1696                fs.mInstance = null;
1697            } else {
1698                if (DEBUG) Log.v(TAG, "restoreAllState: adding #" + i + ": (null)");
1699                mActive.add(null);
1700                if (mAvailIndices == null) {
1701                    mAvailIndices = new ArrayList<Integer>();
1702                }
1703                if (DEBUG) Log.v(TAG, "restoreAllState: adding avail #" + i);
1704                mAvailIndices.add(i);
1705            }
1706        }
1707
1708        // Update the target of all retained fragments.
1709        if (nonConfig != null) {
1710            for (int i=0; i<nonConfig.size(); i++) {
1711                Fragment f = nonConfig.get(i);
1712                if (f.mTargetIndex >= 0) {
1713                    if (f.mTargetIndex < mActive.size()) {
1714                        f.mTarget = mActive.get(f.mTargetIndex);
1715                    } else {
1716                        Log.w(TAG, "Re-attaching retained fragment " + f
1717                                + " target no longer exists: " + f.mTargetIndex);
1718                        f.mTarget = null;
1719                    }
1720                }
1721            }
1722        }
1723
1724        // Build the list of currently added fragments.
1725        if (fms.mAdded != null) {
1726            mAdded = new ArrayList<Fragment>(fms.mAdded.length);
1727            for (int i=0; i<fms.mAdded.length; i++) {
1728                Fragment f = mActive.get(fms.mAdded[i]);
1729                if (f == null) {
1730                    throw new IllegalStateException(
1731                            "No instantiated fragment for index #" + fms.mAdded[i]);
1732                }
1733                f.mAdded = true;
1734                if (DEBUG) Log.v(TAG, "restoreAllState: making added #" + i + ": " + f);
1735                mAdded.add(f);
1736            }
1737        } else {
1738            mAdded = null;
1739        }
1740
1741        // Build the back stack.
1742        if (fms.mBackStack != null) {
1743            mBackStack = new ArrayList<BackStackRecord>(fms.mBackStack.length);
1744            for (int i=0; i<fms.mBackStack.length; i++) {
1745                BackStackRecord bse = fms.mBackStack[i].instantiate(this);
1746                if (DEBUG) Log.v(TAG, "restoreAllState: adding bse #" + i
1747                        + " (index " + bse.mIndex + "): " + bse);
1748                mBackStack.add(bse);
1749                if (bse.mIndex >= 0) {
1750                    setBackStackIndex(bse.mIndex, bse);
1751                }
1752            }
1753        } else {
1754            mBackStack = null;
1755        }
1756    }
1757
1758    public void attachActivity(FragmentActivity activity) {
1759        if (mActivity != null) throw new IllegalStateException();
1760        mActivity = activity;
1761    }
1762
1763    public void noteStateNotSaved() {
1764        mStateSaved = false;
1765    }
1766
1767    public void dispatchCreate() {
1768        mStateSaved = false;
1769        moveToState(Fragment.CREATED, false);
1770    }
1771
1772    public void dispatchActivityCreated() {
1773        mStateSaved = false;
1774        moveToState(Fragment.ACTIVITY_CREATED, false);
1775    }
1776
1777    public void dispatchStart() {
1778        mStateSaved = false;
1779        moveToState(Fragment.STARTED, false);
1780    }
1781
1782    public void dispatchResume() {
1783        mStateSaved = false;
1784        moveToState(Fragment.RESUMED, false);
1785    }
1786
1787    public void dispatchPause() {
1788        moveToState(Fragment.STARTED, false);
1789    }
1790
1791    public void dispatchStop() {
1792        // See saveAllState() for the explanation of this.  We do this for
1793        // all platform versions, to keep our behavior more consistent between
1794        // them.
1795        mStateSaved = true;
1796
1797        moveToState(Fragment.STOPPED, false);
1798    }
1799
1800    public void dispatchReallyStop() {
1801        moveToState(Fragment.ACTIVITY_CREATED, false);
1802    }
1803
1804    public void dispatchDestroy() {
1805        mDestroyed = true;
1806        execPendingActions();
1807        moveToState(Fragment.INITIALIZING, false);
1808        mActivity = null;
1809    }
1810
1811    public void dispatchConfigurationChanged(Configuration newConfig) {
1812        if (mActive != null) {
1813            for (int i=0; i<mAdded.size(); i++) {
1814                Fragment f = mAdded.get(i);
1815                if (f != null) {
1816                    f.onConfigurationChanged(newConfig);
1817                }
1818            }
1819        }
1820    }
1821
1822    public void dispatchLowMemory() {
1823        if (mActive != null) {
1824            for (int i=0; i<mAdded.size(); i++) {
1825                Fragment f = mAdded.get(i);
1826                if (f != null) {
1827                    f.onLowMemory();
1828                }
1829            }
1830        }
1831    }
1832
1833    public boolean dispatchCreateOptionsMenu(Menu menu, MenuInflater inflater) {
1834        boolean show = false;
1835        ArrayList<Fragment> newMenus = null;
1836        if (mActive != null) {
1837            for (int i=0; i<mAdded.size(); i++) {
1838                Fragment f = mAdded.get(i);
1839                if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible) {
1840                    show = true;
1841                    f.onCreateOptionsMenu(menu, inflater);
1842                    if (newMenus == null) {
1843                        newMenus = new ArrayList<Fragment>();
1844                    }
1845                    newMenus.add(f);
1846                }
1847            }
1848        }
1849
1850        if (mCreatedMenus != null) {
1851            for (int i=0; i<mCreatedMenus.size(); i++) {
1852                Fragment f = mCreatedMenus.get(i);
1853                if (newMenus == null || !newMenus.contains(f)) {
1854                    f.onDestroyOptionsMenu();
1855                }
1856            }
1857        }
1858
1859        mCreatedMenus = newMenus;
1860
1861        return show;
1862    }
1863
1864    public boolean dispatchPrepareOptionsMenu(Menu menu) {
1865        boolean show = false;
1866        if (mActive != null) {
1867            for (int i=0; i<mAdded.size(); i++) {
1868                Fragment f = mAdded.get(i);
1869                if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible) {
1870                    show = true;
1871                    f.onPrepareOptionsMenu(menu);
1872                }
1873            }
1874        }
1875        return show;
1876    }
1877
1878    public boolean dispatchOptionsItemSelected(MenuItem item) {
1879        if (mActive != null) {
1880            for (int i=0; i<mAdded.size(); i++) {
1881                Fragment f = mAdded.get(i);
1882                if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible) {
1883                    if (f.onOptionsItemSelected(item)) {
1884                        return true;
1885                    }
1886                }
1887            }
1888        }
1889        return false;
1890    }
1891
1892    public boolean dispatchContextItemSelected(MenuItem item) {
1893        if (mActive != null) {
1894            for (int i=0; i<mAdded.size(); i++) {
1895                Fragment f = mAdded.get(i);
1896                if (f != null && !f.mHidden) {
1897                    if (f.onContextItemSelected(item)) {
1898                        return true;
1899                    }
1900                }
1901            }
1902        }
1903        return false;
1904    }
1905
1906    public void dispatchOptionsMenuClosed(Menu menu) {
1907        if (mActive != null) {
1908            for (int i=0; i<mAdded.size(); i++) {
1909                Fragment f = mAdded.get(i);
1910                if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible) {
1911                    f.onOptionsMenuClosed(menu);
1912                }
1913            }
1914        }
1915    }
1916
1917    public static int reverseTransit(int transit) {
1918        int rev = 0;
1919        switch (transit) {
1920            case FragmentTransaction.TRANSIT_FRAGMENT_OPEN:
1921                rev = FragmentTransaction.TRANSIT_FRAGMENT_CLOSE;
1922                break;
1923            case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE:
1924                rev = FragmentTransaction.TRANSIT_FRAGMENT_OPEN;
1925                break;
1926            case FragmentTransaction.TRANSIT_FRAGMENT_FADE:
1927                rev = FragmentTransaction.TRANSIT_FRAGMENT_FADE;
1928                break;
1929        }
1930        return rev;
1931
1932    }
1933
1934    public static final int ANIM_STYLE_OPEN_ENTER = 1;
1935    public static final int ANIM_STYLE_OPEN_EXIT = 2;
1936    public static final int ANIM_STYLE_CLOSE_ENTER = 3;
1937    public static final int ANIM_STYLE_CLOSE_EXIT = 4;
1938    public static final int ANIM_STYLE_FADE_ENTER = 5;
1939    public static final int ANIM_STYLE_FADE_EXIT = 6;
1940
1941    public static int transitToStyleIndex(int transit, boolean enter) {
1942        int animAttr = -1;
1943        switch (transit) {
1944            case FragmentTransaction.TRANSIT_FRAGMENT_OPEN:
1945                animAttr = enter ? ANIM_STYLE_OPEN_ENTER : ANIM_STYLE_OPEN_EXIT;
1946                break;
1947            case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE:
1948                animAttr = enter ? ANIM_STYLE_CLOSE_ENTER : ANIM_STYLE_CLOSE_EXIT;
1949                break;
1950            case FragmentTransaction.TRANSIT_FRAGMENT_FADE:
1951                animAttr = enter ? ANIM_STYLE_FADE_ENTER : ANIM_STYLE_FADE_EXIT;
1952                break;
1953        }
1954        return animAttr;
1955    }
1956}
1957