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