FragmentManager.java revision e8b402b00c0cbdac050c349a5fc89c34580f3185
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                mTmpActions[i] = null;
1361            }
1362            mExecutingActions = false;
1363            didSomething = true;
1364        }
1365    }
1366
1367    void reportBackStackChanged() {
1368        if (mBackStackChangeListeners != null) {
1369            for (int i=0; i<mBackStackChangeListeners.size(); i++) {
1370                mBackStackChangeListeners.get(i).onBackStackChanged();
1371            }
1372        }
1373    }
1374
1375    void addBackStackState(BackStackRecord state) {
1376        if (mBackStack == null) {
1377            mBackStack = new ArrayList<BackStackRecord>();
1378        }
1379        mBackStack.add(state);
1380        reportBackStackChanged();
1381    }
1382
1383    boolean popBackStackState(Handler handler, String name, int id, int flags) {
1384        if (mBackStack == null) {
1385            return false;
1386        }
1387        if (name == null && id < 0 && (flags&POP_BACK_STACK_INCLUSIVE) == 0) {
1388            int last = mBackStack.size()-1;
1389            if (last < 0) {
1390                return false;
1391            }
1392            final BackStackRecord bss = mBackStack.remove(last);
1393            bss.popFromBackStack(true);
1394            reportBackStackChanged();
1395        } else {
1396            int index = -1;
1397            if (name != null || id >= 0) {
1398                // If a name or ID is specified, look for that place in
1399                // the stack.
1400                index = mBackStack.size()-1;
1401                while (index >= 0) {
1402                    BackStackRecord bss = mBackStack.get(index);
1403                    if (name != null && name.equals(bss.getName())) {
1404                        break;
1405                    }
1406                    if (id >= 0 && id == bss.mIndex) {
1407                        break;
1408                    }
1409                    index--;
1410                }
1411                if (index < 0) {
1412                    return false;
1413                }
1414                if ((flags&POP_BACK_STACK_INCLUSIVE) != 0) {
1415                    index--;
1416                    // Consume all following entries that match.
1417                    while (index >= 0) {
1418                        BackStackRecord bss = mBackStack.get(index);
1419                        if ((name != null && name.equals(bss.getName()))
1420                                || (id >= 0 && id == bss.mIndex)) {
1421                            index--;
1422                            continue;
1423                        }
1424                        break;
1425                    }
1426                }
1427            }
1428            if (index == mBackStack.size()-1) {
1429                return false;
1430            }
1431            final ArrayList<BackStackRecord> states
1432                    = new ArrayList<BackStackRecord>();
1433            for (int i=mBackStack.size()-1; i>index; i--) {
1434                states.add(mBackStack.remove(i));
1435            }
1436            final int LAST = states.size()-1;
1437            for (int i=0; i<=LAST; i++) {
1438                if (DEBUG) Log.v(TAG, "Popping back stack state: " + states.get(i));
1439                states.get(i).popFromBackStack(i == LAST);
1440            }
1441            reportBackStackChanged();
1442        }
1443        return true;
1444    }
1445
1446    ArrayList<Fragment> retainNonConfig() {
1447        ArrayList<Fragment> fragments = null;
1448        if (mActive != null) {
1449            for (int i=0; i<mActive.size(); i++) {
1450                Fragment f = mActive.get(i);
1451                if (f != null && f.mRetainInstance) {
1452                    if (fragments == null) {
1453                        fragments = new ArrayList<Fragment>();
1454                    }
1455                    fragments.add(f);
1456                    f.mRetaining = true;
1457                    f.mTargetIndex = f.mTarget != null ? f.mTarget.mIndex : -1;
1458                }
1459            }
1460        }
1461        return fragments;
1462    }
1463
1464    void saveFragmentViewState(Fragment f) {
1465        if (f.mInnerView == null) {
1466            return;
1467        }
1468        if (mStateArray == null) {
1469            mStateArray = new SparseArray<Parcelable>();
1470        } else {
1471            mStateArray.clear();
1472        }
1473        f.mInnerView.saveHierarchyState(mStateArray);
1474        if (mStateArray.size() > 0) {
1475            f.mSavedViewState = mStateArray;
1476            mStateArray = null;
1477        }
1478    }
1479
1480    Bundle saveFragmentBasicState(Fragment f) {
1481        Bundle result = null;
1482
1483        if (mStateBundle == null) {
1484            mStateBundle = new Bundle();
1485        }
1486        f.onSaveInstanceState(mStateBundle);
1487        if (!mStateBundle.isEmpty()) {
1488            result = mStateBundle;
1489            mStateBundle = null;
1490        }
1491
1492        if (f.mView != null) {
1493            saveFragmentViewState(f);
1494        }
1495        if (f.mSavedViewState != null) {
1496            if (result == null) {
1497                result = new Bundle();
1498            }
1499            result.putSparseParcelableArray(
1500                    FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState);
1501        }
1502
1503        return result;
1504    }
1505
1506    Parcelable saveAllState() {
1507        // Make sure all pending operations have now been executed to get
1508        // our state update-to-date.
1509        execPendingActions();
1510
1511        if (HONEYCOMB) {
1512            // As of Honeycomb, we save state after pausing.  Prior to that
1513            // it is before pausing.  With fragments this is an issue, since
1514            // there are many things you may do after pausing but before
1515            // stopping that change the fragment state.  For those older
1516            // devices, we will not at this point say that we have saved
1517            // the state, so we will allow them to continue doing fragment
1518            // transactions.  This retains the same semantics as Honeycomb,
1519            // though you do have the risk of losing the very most recent state
1520            // if the process is killed...  we'll live with that.
1521            mStateSaved = true;
1522        }
1523
1524        if (mActive == null || mActive.size() <= 0) {
1525            return null;
1526        }
1527
1528        // First collect all active fragments.
1529        int N = mActive.size();
1530        FragmentState[] active = new FragmentState[N];
1531        boolean haveFragments = false;
1532        for (int i=0; i<N; i++) {
1533            Fragment f = mActive.get(i);
1534            if (f != null) {
1535                haveFragments = true;
1536
1537                FragmentState fs = new FragmentState(f);
1538                active[i] = fs;
1539
1540                if (f.mState > Fragment.INITIALIZING && fs.mSavedFragmentState == null) {
1541                    fs.mSavedFragmentState = saveFragmentBasicState(f);
1542
1543                    if (f.mTarget != null) {
1544                        if (f.mTarget.mIndex < 0) {
1545                            String msg = "Failure saving state: " + f
1546                                + " has target not in fragment manager: " + f.mTarget;
1547                            Log.e(TAG, msg);
1548                            dump("  ", null, new PrintWriter(new LogWriter(TAG)), new String[] { });
1549                            throw new IllegalStateException(msg);
1550                        }
1551                        if (fs.mSavedFragmentState == null) {
1552                            fs.mSavedFragmentState = new Bundle();
1553                        }
1554                        putFragment(fs.mSavedFragmentState,
1555                                FragmentManagerImpl.TARGET_STATE_TAG, f.mTarget);
1556                        if (f.mTargetRequestCode != 0) {
1557                            fs.mSavedFragmentState.putInt(
1558                                    FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG,
1559                                    f.mTargetRequestCode);
1560                        }
1561                    }
1562
1563                } else {
1564                    fs.mSavedFragmentState = f.mSavedFragmentState;
1565                }
1566
1567                if (DEBUG) Log.v(TAG, "Saved state of " + f + ": "
1568                        + fs.mSavedFragmentState);
1569            }
1570        }
1571
1572        if (!haveFragments) {
1573            if (DEBUG) Log.v(TAG, "saveAllState: no fragments!");
1574            return null;
1575        }
1576
1577        int[] added = null;
1578        BackStackState[] backStack = null;
1579
1580        // Build list of currently added fragments.
1581        if (mAdded != null) {
1582            N = mAdded.size();
1583            if (N > 0) {
1584                added = new int[N];
1585                for (int i=0; i<N; i++) {
1586                    added[i] = mAdded.get(i).mIndex;
1587                    if (DEBUG) Log.v(TAG, "saveAllState: adding fragment #" + i
1588                            + ": " + mAdded.get(i));
1589                }
1590            }
1591        }
1592
1593        // Now save back stack.
1594        if (mBackStack != null) {
1595            N = mBackStack.size();
1596            if (N > 0) {
1597                backStack = new BackStackState[N];
1598                for (int i=0; i<N; i++) {
1599                    backStack[i] = new BackStackState(this, mBackStack.get(i));
1600                    if (DEBUG) Log.v(TAG, "saveAllState: adding back stack #" + i
1601                            + ": " + mBackStack.get(i));
1602                }
1603            }
1604        }
1605
1606        FragmentManagerState fms = new FragmentManagerState();
1607        fms.mActive = active;
1608        fms.mAdded = added;
1609        fms.mBackStack = backStack;
1610        return fms;
1611    }
1612
1613    void restoreAllState(Parcelable state, ArrayList<Fragment> nonConfig) {
1614        // If there is no saved state at all, then there can not be
1615        // any nonConfig fragments either, so that is that.
1616        if (state == null) return;
1617        FragmentManagerState fms = (FragmentManagerState)state;
1618        if (fms.mActive == null) return;
1619
1620        // First re-attach any non-config instances we are retaining back
1621        // to their saved state, so we don't try to instantiate them again.
1622        if (nonConfig != null) {
1623            for (int i=0; i<nonConfig.size(); i++) {
1624                Fragment f = nonConfig.get(i);
1625                if (DEBUG) Log.v(TAG, "restoreAllState: re-attaching retained " + f);
1626                FragmentState fs = fms.mActive[f.mIndex];
1627                fs.mInstance = f;
1628                f.mSavedViewState = null;
1629                f.mBackStackNesting = 0;
1630                f.mInLayout = false;
1631                f.mAdded = false;
1632                f.mTarget = null;
1633                if (fs.mSavedFragmentState != null) {
1634                    fs.mSavedFragmentState.setClassLoader(mActivity.getClassLoader());
1635                    f.mSavedViewState = fs.mSavedFragmentState.getSparseParcelableArray(
1636                            FragmentManagerImpl.VIEW_STATE_TAG);
1637                }
1638            }
1639        }
1640
1641        // Build the full list of active fragments, instantiating them from
1642        // their saved state.
1643        mActive = new ArrayList<Fragment>(fms.mActive.length);
1644        if (mAvailIndices != null) {
1645            mAvailIndices.clear();
1646        }
1647        for (int i=0; i<fms.mActive.length; i++) {
1648            FragmentState fs = fms.mActive[i];
1649            if (fs != null) {
1650                Fragment f = fs.instantiate(mActivity);
1651                if (DEBUG) Log.v(TAG, "restoreAllState: adding #" + i + ": " + f);
1652                mActive.add(f);
1653                // Now that the fragment is instantiated (or came from being
1654                // retained above), clear mInstance in case we end up re-restoring
1655                // from this FragmentState again.
1656                fs.mInstance = null;
1657            } else {
1658                if (DEBUG) Log.v(TAG, "restoreAllState: adding #" + i + ": (null)");
1659                mActive.add(null);
1660                if (mAvailIndices == null) {
1661                    mAvailIndices = new ArrayList<Integer>();
1662                }
1663                if (DEBUG) Log.v(TAG, "restoreAllState: adding avail #" + i);
1664                mAvailIndices.add(i);
1665            }
1666        }
1667
1668        // Update the target of all retained fragments.
1669        if (nonConfig != null) {
1670            for (int i=0; i<nonConfig.size(); i++) {
1671                Fragment f = nonConfig.get(i);
1672                if (f.mTargetIndex >= 0) {
1673                    if (f.mTargetIndex < mActive.size()) {
1674                        f.mTarget = mActive.get(f.mTargetIndex);
1675                    } else {
1676                        Log.w(TAG, "Re-attaching retained fragment " + f
1677                                + " target no longer exists: " + f.mTargetIndex);
1678                        f.mTarget = null;
1679                    }
1680                }
1681            }
1682        }
1683
1684        // Build the list of currently added fragments.
1685        if (fms.mAdded != null) {
1686            mAdded = new ArrayList<Fragment>(fms.mAdded.length);
1687            for (int i=0; i<fms.mAdded.length; i++) {
1688                Fragment f = mActive.get(fms.mAdded[i]);
1689                if (f == null) {
1690                    throw new IllegalStateException(
1691                            "No instantiated fragment for index #" + fms.mAdded[i]);
1692                }
1693                f.mAdded = true;
1694                f.mImmediateActivity = mActivity;
1695                if (DEBUG) Log.v(TAG, "restoreAllState: making added #" + i + ": " + f);
1696                mAdded.add(f);
1697            }
1698        } else {
1699            mAdded = null;
1700        }
1701
1702        // Build the back stack.
1703        if (fms.mBackStack != null) {
1704            mBackStack = new ArrayList<BackStackRecord>(fms.mBackStack.length);
1705            for (int i=0; i<fms.mBackStack.length; i++) {
1706                BackStackRecord bse = fms.mBackStack[i].instantiate(this);
1707                if (DEBUG) Log.v(TAG, "restoreAllState: adding bse #" + i
1708                        + " (index " + bse.mIndex + "): " + bse);
1709                mBackStack.add(bse);
1710                if (bse.mIndex >= 0) {
1711                    setBackStackIndex(bse.mIndex, bse);
1712                }
1713            }
1714        } else {
1715            mBackStack = null;
1716        }
1717    }
1718
1719    public void attachActivity(FragmentActivity activity) {
1720        if (mActivity != null) throw new IllegalStateException();
1721        mActivity = activity;
1722    }
1723
1724    public void noteStateNotSaved() {
1725        mStateSaved = false;
1726    }
1727
1728    public void dispatchCreate() {
1729        mStateSaved = false;
1730        moveToState(Fragment.CREATED, false);
1731    }
1732
1733    public void dispatchActivityCreated() {
1734        mStateSaved = false;
1735        moveToState(Fragment.ACTIVITY_CREATED, false);
1736    }
1737
1738    public void dispatchStart() {
1739        mStateSaved = false;
1740        moveToState(Fragment.STARTED, false);
1741    }
1742
1743    public void dispatchResume() {
1744        mStateSaved = false;
1745        moveToState(Fragment.RESUMED, false);
1746    }
1747
1748    public void dispatchPause() {
1749        moveToState(Fragment.STARTED, false);
1750    }
1751
1752    public void dispatchStop() {
1753        // See saveAllState() for the explanation of this.  We do this for
1754        // all platform versions, to keep our behavior more consistent between
1755        // them.
1756        mStateSaved = true;
1757
1758        moveToState(Fragment.STOPPED, false);
1759    }
1760
1761    public void dispatchReallyStop(boolean retaining) {
1762        if (mActive != null) {
1763            for (int i=0; i<mAdded.size(); i++) {
1764                Fragment f = mAdded.get(i);
1765                if (f != null) {
1766                    f.performReallyStop(retaining);
1767                }
1768            }
1769        }
1770    }
1771
1772    public void dispatchDestroy() {
1773        mDestroyed = true;
1774        execPendingActions();
1775        moveToState(Fragment.INITIALIZING, false);
1776        mActivity = null;
1777    }
1778
1779    public void dispatchConfigurationChanged(Configuration newConfig) {
1780        if (mActive != null) {
1781            for (int i=0; i<mAdded.size(); i++) {
1782                Fragment f = mAdded.get(i);
1783                if (f != null) {
1784                    f.onConfigurationChanged(newConfig);
1785                }
1786            }
1787        }
1788    }
1789
1790    public void dispatchLowMemory() {
1791        if (mActive != null) {
1792            for (int i=0; i<mAdded.size(); i++) {
1793                Fragment f = mAdded.get(i);
1794                if (f != null) {
1795                    f.onLowMemory();
1796                }
1797            }
1798        }
1799    }
1800
1801    public boolean dispatchCreateOptionsMenu(Menu menu, MenuInflater inflater) {
1802        boolean show = false;
1803        ArrayList<Fragment> newMenus = null;
1804        if (mActive != null) {
1805            for (int i=0; i<mAdded.size(); i++) {
1806                Fragment f = mAdded.get(i);
1807                if (f != null && !f.mHidden && f.mHasMenu) {
1808                    show = true;
1809                    f.onCreateOptionsMenu(menu, inflater);
1810                    if (newMenus == null) {
1811                        newMenus = new ArrayList<Fragment>();
1812                    }
1813                    newMenus.add(f);
1814                }
1815            }
1816        }
1817
1818        if (mCreatedMenus != null) {
1819            for (int i=0; i<mCreatedMenus.size(); i++) {
1820                Fragment f = mCreatedMenus.get(i);
1821                if (newMenus == null || !newMenus.contains(f)) {
1822                    f.onDestroyOptionsMenu();
1823                }
1824            }
1825        }
1826
1827        mCreatedMenus = newMenus;
1828
1829        return show;
1830    }
1831
1832    public boolean dispatchPrepareOptionsMenu(Menu menu) {
1833        boolean show = false;
1834        if (mActive != null) {
1835            for (int i=0; i<mAdded.size(); i++) {
1836                Fragment f = mAdded.get(i);
1837                if (f != null && !f.mHidden && f.mHasMenu) {
1838                    show = true;
1839                    f.onPrepareOptionsMenu(menu);
1840                }
1841            }
1842        }
1843        return show;
1844    }
1845
1846    public boolean dispatchOptionsItemSelected(MenuItem item) {
1847        if (mActive != null) {
1848            for (int i=0; i<mAdded.size(); i++) {
1849                Fragment f = mAdded.get(i);
1850                if (f != null && !f.mHidden && f.mHasMenu) {
1851                    if (f.onOptionsItemSelected(item)) {
1852                        return true;
1853                    }
1854                }
1855            }
1856        }
1857        return false;
1858    }
1859
1860    public boolean dispatchContextItemSelected(MenuItem item) {
1861        if (mActive != null) {
1862            for (int i=0; i<mAdded.size(); i++) {
1863                Fragment f = mAdded.get(i);
1864                if (f != null && !f.mHidden) {
1865                    if (f.onContextItemSelected(item)) {
1866                        return true;
1867                    }
1868                }
1869            }
1870        }
1871        return false;
1872    }
1873
1874    public void dispatchOptionsMenuClosed(Menu menu) {
1875        if (mActive != null) {
1876            for (int i=0; i<mAdded.size(); i++) {
1877                Fragment f = mAdded.get(i);
1878                if (f != null && !f.mHidden && f.mHasMenu) {
1879                    f.onOptionsMenuClosed(menu);
1880                }
1881            }
1882        }
1883    }
1884
1885    public static int reverseTransit(int transit) {
1886        int rev = 0;
1887        switch (transit) {
1888            case FragmentTransaction.TRANSIT_FRAGMENT_OPEN:
1889                rev = FragmentTransaction.TRANSIT_FRAGMENT_CLOSE;
1890                break;
1891            case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE:
1892                rev = FragmentTransaction.TRANSIT_FRAGMENT_OPEN;
1893                break;
1894            case FragmentTransaction.TRANSIT_FRAGMENT_FADE:
1895                rev = FragmentTransaction.TRANSIT_FRAGMENT_FADE;
1896                break;
1897        }
1898        return rev;
1899
1900    }
1901
1902    public static final int ANIM_STYLE_OPEN_ENTER = 1;
1903    public static final int ANIM_STYLE_OPEN_EXIT = 2;
1904    public static final int ANIM_STYLE_CLOSE_ENTER = 3;
1905    public static final int ANIM_STYLE_CLOSE_EXIT = 4;
1906    public static final int ANIM_STYLE_FADE_ENTER = 5;
1907    public static final int ANIM_STYLE_FADE_EXIT = 6;
1908
1909    public static int transitToStyleIndex(int transit, boolean enter) {
1910        int animAttr = -1;
1911        switch (transit) {
1912            case FragmentTransaction.TRANSIT_FRAGMENT_OPEN:
1913                animAttr = enter ? ANIM_STYLE_OPEN_ENTER : ANIM_STYLE_OPEN_EXIT;
1914                break;
1915            case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE:
1916                animAttr = enter ? ANIM_STYLE_CLOSE_ENTER : ANIM_STYLE_CLOSE_EXIT;
1917                break;
1918            case FragmentTransaction.TRANSIT_FRAGMENT_FADE:
1919                animAttr = enter ? ANIM_STYLE_FADE_ENTER : ANIM_STYLE_FADE_EXIT;
1920                break;
1921        }
1922        return animAttr;
1923    }
1924}
1925