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