Fragment.java revision 62bea2f1710be0d1a42c07109fd4307ded660d3b
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
17package android.app;
18
19import android.animation.Animator;
20import android.content.ComponentCallbacks2;
21import android.content.Context;
22import android.content.Intent;
23import android.content.res.Configuration;
24import android.content.res.Resources;
25import android.os.Bundle;
26import android.os.Parcel;
27import android.os.Parcelable;
28import android.util.AndroidRuntimeException;
29import android.util.AttributeSet;
30import android.util.DebugUtils;
31import android.util.Log;
32import android.util.SparseArray;
33import android.view.ContextMenu;
34import android.view.ContextMenu.ContextMenuInfo;
35import android.view.LayoutInflater;
36import android.view.Menu;
37import android.view.MenuInflater;
38import android.view.MenuItem;
39import android.view.View;
40import android.view.View.OnCreateContextMenuListener;
41import android.view.ViewGroup;
42import android.widget.AdapterView;
43
44import java.io.FileDescriptor;
45import java.io.PrintWriter;
46import java.util.HashMap;
47
48final class FragmentState implements Parcelable {
49    final String mClassName;
50    final int mIndex;
51    final boolean mFromLayout;
52    final int mFragmentId;
53    final int mContainerId;
54    final String mTag;
55    final boolean mRetainInstance;
56    final boolean mDetached;
57    final Bundle mArguments;
58
59    Bundle mSavedFragmentState;
60
61    Fragment mInstance;
62
63    public FragmentState(Fragment frag) {
64        mClassName = frag.getClass().getName();
65        mIndex = frag.mIndex;
66        mFromLayout = frag.mFromLayout;
67        mFragmentId = frag.mFragmentId;
68        mContainerId = frag.mContainerId;
69        mTag = frag.mTag;
70        mRetainInstance = frag.mRetainInstance;
71        mDetached = frag.mDetached;
72        mArguments = frag.mArguments;
73    }
74
75    public FragmentState(Parcel in) {
76        mClassName = in.readString();
77        mIndex = in.readInt();
78        mFromLayout = in.readInt() != 0;
79        mFragmentId = in.readInt();
80        mContainerId = in.readInt();
81        mTag = in.readString();
82        mRetainInstance = in.readInt() != 0;
83        mDetached = in.readInt() != 0;
84        mArguments = in.readBundle();
85        mSavedFragmentState = in.readBundle();
86    }
87
88    public Fragment instantiate(Activity activity, Fragment parent) {
89        if (mInstance != null) {
90            return mInstance;
91        }
92
93        if (mArguments != null) {
94            mArguments.setClassLoader(activity.getClassLoader());
95        }
96
97        mInstance = Fragment.instantiate(activity, mClassName, mArguments);
98
99        if (mSavedFragmentState != null) {
100            mSavedFragmentState.setClassLoader(activity.getClassLoader());
101            mInstance.mSavedFragmentState = mSavedFragmentState;
102        }
103        mInstance.setIndex(mIndex, parent);
104        mInstance.mFromLayout = mFromLayout;
105        mInstance.mRestored = true;
106        mInstance.mFragmentId = mFragmentId;
107        mInstance.mContainerId = mContainerId;
108        mInstance.mTag = mTag;
109        mInstance.mRetainInstance = mRetainInstance;
110        mInstance.mDetached = mDetached;
111        mInstance.mFragmentManager = activity.mFragments;
112        if (FragmentManagerImpl.DEBUG) Log.v(FragmentManagerImpl.TAG,
113                "Instantiated fragment " + mInstance);
114
115        return mInstance;
116    }
117
118    public int describeContents() {
119        return 0;
120    }
121
122    public void writeToParcel(Parcel dest, int flags) {
123        dest.writeString(mClassName);
124        dest.writeInt(mIndex);
125        dest.writeInt(mFromLayout ? 1 : 0);
126        dest.writeInt(mFragmentId);
127        dest.writeInt(mContainerId);
128        dest.writeString(mTag);
129        dest.writeInt(mRetainInstance ? 1 : 0);
130        dest.writeInt(mDetached ? 1 : 0);
131        dest.writeBundle(mArguments);
132        dest.writeBundle(mSavedFragmentState);
133    }
134
135    public static final Parcelable.Creator<FragmentState> CREATOR
136            = new Parcelable.Creator<FragmentState>() {
137        public FragmentState createFromParcel(Parcel in) {
138            return new FragmentState(in);
139        }
140
141        public FragmentState[] newArray(int size) {
142            return new FragmentState[size];
143        }
144    };
145}
146
147/**
148 * A Fragment is a piece of an application's user interface or behavior
149 * that can be placed in an {@link Activity}.  Interaction with fragments
150 * is done through {@link FragmentManager}, which can be obtained via
151 * {@link Activity#getFragmentManager() Activity.getFragmentManager()} and
152 * {@link Fragment#getFragmentManager() Fragment.getFragmentManager()}.
153 *
154 * <p>The Fragment class can be used many ways to achieve a wide variety of
155 * results. In its core, it represents a particular operation or interface
156 * that is running within a larger {@link Activity}.  A Fragment is closely
157 * tied to the Activity it is in, and can not be used apart from one.  Though
158 * Fragment defines its own lifecycle, that lifecycle is dependent on its
159 * activity: if the activity is stopped, no fragments inside of it can be
160 * started; when the activity is destroyed, all fragments will be destroyed.
161 *
162 * <p>All subclasses of Fragment must include a public empty constructor.
163 * The framework will often re-instantiate a fragment class when needed,
164 * in particular during state restore, and needs to be able to find this
165 * constructor to instantiate it.  If the empty constructor is not available,
166 * a runtime exception will occur in some cases during state restore.
167 *
168 * <p>Topics covered here:
169 * <ol>
170 * <li><a href="#OlderPlatforms">Older Platforms</a>
171 * <li><a href="#Lifecycle">Lifecycle</a>
172 * <li><a href="#Layout">Layout</a>
173 * <li><a href="#BackStack">Back Stack</a>
174 * </ol>
175 *
176 * <div class="special reference">
177 * <h3>Developer Guides</h3>
178 * <p>For more information about using fragments, read the
179 * <a href="{@docRoot}guide/topics/fundamentals/fragments.html">Fragments</a> developer guide.</p>
180 * </div>
181 *
182 * <a name="OlderPlatforms"></a>
183 * <h3>Older Platforms</h3>
184 *
185 * While the Fragment API was introduced in
186 * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, a version of the API
187 * at is also available for use on older platforms through
188 * {@link android.support.v4.app.FragmentActivity}.  See the blog post
189 * <a href="http://android-developers.blogspot.com/2011/03/fragments-for-all.html">
190 * Fragments For All</a> for more details.
191 *
192 * <a name="Lifecycle"></a>
193 * <h3>Lifecycle</h3>
194 *
195 * <p>Though a Fragment's lifecycle is tied to its owning activity, it has
196 * its own wrinkle on the standard activity lifecycle.  It includes basic
197 * activity lifecycle methods such as {@link #onResume}, but also important
198 * are methods related to interactions with the activity and UI generation.
199 *
200 * <p>The core series of lifecycle methods that are called to bring a fragment
201 * up to resumed state (interacting with the user) are:
202 *
203 * <ol>
204 * <li> {@link #onAttach} called once the fragment is associated with its activity.
205 * <li> {@link #onCreate} called to do initial creation of the fragment.
206 * <li> {@link #onCreateView} creates and returns the view hierarchy associated
207 * with the fragment.
208 * <li> {@link #onActivityCreated} tells the fragment that its activity has
209 * completed its own {@link Activity#onCreate Activity.onCreate()}.
210 * <li> {@link #onViewStateRestored} tells the fragment that all of the saved
211 * state of its view hierarchy has been restored.
212 * <li> {@link #onStart} makes the fragment visible to the user (based on its
213 * containing activity being started).
214 * <li> {@link #onResume} makes the fragment interacting with the user (based on its
215 * containing activity being resumed).
216 * </ol>
217 *
218 * <p>As a fragment is no longer being used, it goes through a reverse
219 * series of callbacks:
220 *
221 * <ol>
222 * <li> {@link #onPause} fragment is no longer interacting with the user either
223 * because its activity is being paused or a fragment operation is modifying it
224 * in the activity.
225 * <li> {@link #onStop} fragment is no longer visible to the user either
226 * because its activity is being stopped or a fragment operation is modifying it
227 * in the activity.
228 * <li> {@link #onDestroyView} allows the fragment to clean up resources
229 * associated with its View.
230 * <li> {@link #onDestroy} called to do final cleanup of the fragment's state.
231 * <li> {@link #onDetach} called immediately prior to the fragment no longer
232 * being associated with its activity.
233 * </ol>
234 *
235 * <a name="Layout"></a>
236 * <h3>Layout</h3>
237 *
238 * <p>Fragments can be used as part of your application's layout, allowing
239 * you to better modularize your code and more easily adjust your user
240 * interface to the screen it is running on.  As an example, we can look
241 * at a simple program consisting of a list of items, and display of the
242 * details of each item.</p>
243 *
244 * <p>An activity's layout XML can include <code>&lt;fragment&gt;</code> tags
245 * to embed fragment instances inside of the layout.  For example, here is
246 * a simple layout that embeds one fragment:</p>
247 *
248 * {@sample development/samples/ApiDemos/res/layout/fragment_layout.xml layout}
249 *
250 * <p>The layout is installed in the activity in the normal way:</p>
251 *
252 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
253 *      main}
254 *
255 * <p>The titles fragment, showing a list of titles, is fairly simple, relying
256 * on {@link ListFragment} for most of its work.  Note the implementation of
257 * clicking an item: depending on the current activity's layout, it can either
258 * create and display a new fragment to show the details in-place (more about
259 * this later), or start a new activity to show the details.</p>
260 *
261 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
262 *      titles}
263 *
264 * <p>The details fragment showing the contents of a selected item just
265 * displays a string of text based on an index of a string array built in to
266 * the app:</p>
267 *
268 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
269 *      details}
270 *
271 * <p>In this case when the user clicks on a title, there is no details
272 * container in the current activity, so the titles fragment's click code will
273 * launch a new activity to display the details fragment:</p>
274 *
275 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
276 *      details_activity}
277 *
278 * <p>However the screen may be large enough to show both the list of titles
279 * and details about the currently selected title.  To use such a layout on
280 * a landscape screen, this alternative layout can be placed under layout-land:</p>
281 *
282 * {@sample development/samples/ApiDemos/res/layout-land/fragment_layout.xml layout}
283 *
284 * <p>Note how the prior code will adjust to this alternative UI flow: the titles
285 * fragment will now embed the details fragment inside of this activity, and the
286 * details activity will finish itself if it is running in a configuration
287 * where the details can be shown in-place.
288 *
289 * <p>When a configuration change causes the activity hosting these fragments
290 * to restart, its new instance may use a different layout that doesn't
291 * include the same fragments as the previous layout.  In this case all of
292 * the previous fragments will still be instantiated and running in the new
293 * instance.  However, any that are no longer associated with a &lt;fragment&gt;
294 * tag in the view hierarchy will not have their content view created
295 * and will return false from {@link #isInLayout}.  (The code here also shows
296 * how you can determine if a fragment placed in a container is no longer
297 * running in a layout with that container and avoid creating its view hierarchy
298 * in that case.)
299 *
300 * <p>The attributes of the &lt;fragment&gt; tag are used to control the
301 * LayoutParams provided when attaching the fragment's view to the parent
302 * container.  They can also be parsed by the fragment in {@link #onInflate}
303 * as parameters.
304 *
305 * <p>The fragment being instantiated must have some kind of unique identifier
306 * so that it can be re-associated with a previous instance if the parent
307 * activity needs to be destroyed and recreated.  This can be provided these
308 * ways:
309 *
310 * <ul>
311 * <li>If nothing is explicitly supplied, the view ID of the container will
312 * be used.
313 * <li><code>android:tag</code> can be used in &lt;fragment&gt; to provide
314 * a specific tag name for the fragment.
315 * <li><code>android:id</code> can be used in &lt;fragment&gt; to provide
316 * a specific identifier for the fragment.
317 * </ul>
318 *
319 * <a name="BackStack"></a>
320 * <h3>Back Stack</h3>
321 *
322 * <p>The transaction in which fragments are modified can be placed on an
323 * internal back-stack of the owning activity.  When the user presses back
324 * in the activity, any transactions on the back stack are popped off before
325 * the activity itself is finished.
326 *
327 * <p>For example, consider this simple fragment that is instantiated with
328 * an integer argument and displays that in a TextView in its UI:</p>
329 *
330 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentStack.java
331 *      fragment}
332 *
333 * <p>A function that creates a new instance of the fragment, replacing
334 * whatever current fragment instance is being shown and pushing that change
335 * on to the back stack could be written as:
336 *
337 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentStack.java
338 *      add_stack}
339 *
340 * <p>After each call to this function, a new entry is on the stack, and
341 * pressing back will pop it to return the user to whatever previous state
342 * the activity UI was in.
343 */
344public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListener {
345    private static final HashMap<String, Class<?>> sClassMap =
346            new HashMap<String, Class<?>>();
347
348    static final int INVALID_STATE = -1;   // Invalid state used as a null value.
349    static final int INITIALIZING = 0;     // Not yet created.
350    static final int CREATED = 1;          // Created.
351    static final int ACTIVITY_CREATED = 2; // The activity has finished its creation.
352    static final int STOPPED = 3;          // Fully created, not started.
353    static final int STARTED = 4;          // Created and started, not resumed.
354    static final int RESUMED = 5;          // Created started and resumed.
355
356    int mState = INITIALIZING;
357
358    // Non-null if the fragment's view hierarchy is currently animating away,
359    // meaning we need to wait a bit on completely destroying it.  This is the
360    // animation that is running.
361    Animator mAnimatingAway;
362
363    // If mAnimatingAway != null, this is the state we should move to once the
364    // animation is done.
365    int mStateAfterAnimating;
366
367    // When instantiated from saved state, this is the saved state.
368    Bundle mSavedFragmentState;
369    SparseArray<Parcelable> mSavedViewState;
370
371    // Index into active fragment array.
372    int mIndex = -1;
373
374    // Internal unique name for this fragment;
375    String mWho;
376
377    // Construction arguments;
378    Bundle mArguments;
379
380    // Target fragment.
381    Fragment mTarget;
382
383    // For use when retaining a fragment: this is the index of the last mTarget.
384    int mTargetIndex = -1;
385
386    // Target request code.
387    int mTargetRequestCode;
388
389    // True if the fragment is in the list of added fragments.
390    boolean mAdded;
391
392    // If set this fragment is being removed from its activity.
393    boolean mRemoving;
394
395    // True if the fragment is in the resumed state.
396    boolean mResumed;
397
398    // Set to true if this fragment was instantiated from a layout file.
399    boolean mFromLayout;
400
401    // Set to true when the view has actually been inflated in its layout.
402    boolean mInLayout;
403
404    // True if this fragment has been restored from previously saved state.
405    boolean mRestored;
406
407    // Number of active back stack entries this fragment is in.
408    int mBackStackNesting;
409
410    // The fragment manager we are associated with.  Set as soon as the
411    // fragment is used in a transaction; cleared after it has been removed
412    // from all transactions.
413    FragmentManagerImpl mFragmentManager;
414
415    // Activity this fragment is attached to.
416    Activity mActivity;
417
418    // Private fragment manager for child fragments inside of this one.
419    FragmentManagerImpl mChildFragmentManager;
420
421    // If this Fragment is contained in another Fragment, this is that container.
422    Fragment mParentFragment;
423
424    // The optional identifier for this fragment -- either the container ID if it
425    // was dynamically added to the view hierarchy, or the ID supplied in
426    // layout.
427    int mFragmentId;
428
429    // When a fragment is being dynamically added to the view hierarchy, this
430    // is the identifier of the parent container it is being added to.
431    int mContainerId;
432
433    // The optional named tag for this fragment -- usually used to find
434    // fragments that are not part of the layout.
435    String mTag;
436
437    // Set to true when the app has requested that this fragment be hidden
438    // from the user.
439    boolean mHidden;
440
441    // Set to true when the app has requested that this fragment be detached.
442    boolean mDetached;
443
444    // If set this fragment would like its instance retained across
445    // configuration changes.
446    boolean mRetainInstance;
447
448    // If set this fragment is being retained across the current config change.
449    boolean mRetaining;
450
451    // If set this fragment has menu items to contribute.
452    boolean mHasMenu;
453
454    // Set to true to allow the fragment's menu to be shown.
455    boolean mMenuVisible = true;
456
457    // Used to verify that subclasses call through to super class.
458    boolean mCalled;
459
460    // If app has requested a specific animation, this is the one to use.
461    int mNextAnim;
462
463    // The parent container of the fragment after dynamically added to UI.
464    ViewGroup mContainer;
465
466    // The View generated for this fragment.
467    View mView;
468
469    // Whether this fragment should defer starting until after other fragments
470    // have been started and their loaders are finished.
471    boolean mDeferStart;
472
473    // Hint provided by the app that this fragment is currently visible to the user.
474    boolean mUserVisibleHint = true;
475
476    LoaderManagerImpl mLoaderManager;
477    boolean mLoadersStarted;
478    boolean mCheckedForLoaderManager;
479
480    /**
481     * State information that has been retrieved from a fragment instance
482     * through {@link FragmentManager#saveFragmentInstanceState(Fragment)
483     * FragmentManager.saveFragmentInstanceState}.
484     */
485    public static class SavedState implements Parcelable {
486        final Bundle mState;
487
488        SavedState(Bundle state) {
489            mState = state;
490        }
491
492        SavedState(Parcel in, ClassLoader loader) {
493            mState = in.readBundle();
494            if (loader != null && mState != null) {
495                mState.setClassLoader(loader);
496            }
497        }
498
499        @Override
500        public int describeContents() {
501            return 0;
502        }
503
504        @Override
505        public void writeToParcel(Parcel dest, int flags) {
506            dest.writeBundle(mState);
507        }
508
509        public static final Parcelable.ClassLoaderCreator<SavedState> CREATOR
510                = new Parcelable.ClassLoaderCreator<SavedState>() {
511            public SavedState createFromParcel(Parcel in) {
512                return new SavedState(in, null);
513            }
514
515            public SavedState createFromParcel(Parcel in, ClassLoader loader) {
516                return new SavedState(in, loader);
517            }
518
519            public SavedState[] newArray(int size) {
520                return new SavedState[size];
521            }
522        };
523    }
524
525    /**
526     * Thrown by {@link Fragment#instantiate(Context, String, Bundle)} when
527     * there is an instantiation failure.
528     */
529    static public class InstantiationException extends AndroidRuntimeException {
530        public InstantiationException(String msg, Exception cause) {
531            super(msg, cause);
532        }
533    }
534
535    /**
536     * Default constructor.  <strong>Every</strong> fragment must have an
537     * empty constructor, so it can be instantiated when restoring its
538     * activity's state.  It is strongly recommended that subclasses do not
539     * have other constructors with parameters, since these constructors
540     * will not be called when the fragment is re-instantiated; instead,
541     * arguments can be supplied by the caller with {@link #setArguments}
542     * and later retrieved by the Fragment with {@link #getArguments}.
543     *
544     * <p>Applications should generally not implement a constructor.  The
545     * first place application code an run where the fragment is ready to
546     * be used is in {@link #onAttach(Activity)}, the point where the fragment
547     * is actually associated with its activity.  Some applications may also
548     * want to implement {@link #onInflate} to retrieve attributes from a
549     * layout resource, though should take care here because this happens for
550     * the fragment is attached to its activity.
551     */
552    public Fragment() {
553    }
554
555    /**
556     * Like {@link #instantiate(Context, String, Bundle)} but with a null
557     * argument Bundle.
558     */
559    public static Fragment instantiate(Context context, String fname) {
560        return instantiate(context, fname, null);
561    }
562
563    /**
564     * Create a new instance of a Fragment with the given class name.  This is
565     * the same as calling its empty constructor.
566     *
567     * @param context The calling context being used to instantiate the fragment.
568     * This is currently just used to get its ClassLoader.
569     * @param fname The class name of the fragment to instantiate.
570     * @param args Bundle of arguments to supply to the fragment, which it
571     * can retrieve with {@link #getArguments()}.  May be null.
572     * @return Returns a new fragment instance.
573     * @throws InstantiationException If there is a failure in instantiating
574     * the given fragment class.  This is a runtime exception; it is not
575     * normally expected to happen.
576     */
577    public static Fragment instantiate(Context context, String fname, Bundle args) {
578        try {
579            Class<?> clazz = sClassMap.get(fname);
580            if (clazz == null) {
581                // Class not found in the cache, see if it's real, and try to add it
582                clazz = context.getClassLoader().loadClass(fname);
583                sClassMap.put(fname, clazz);
584            }
585            Fragment f = (Fragment)clazz.newInstance();
586            if (args != null) {
587                args.setClassLoader(f.getClass().getClassLoader());
588                f.mArguments = args;
589            }
590            return f;
591        } catch (ClassNotFoundException e) {
592            throw new InstantiationException("Unable to instantiate fragment " + fname
593                    + ": make sure class name exists, is public, and has an"
594                    + " empty constructor that is public", e);
595        } catch (java.lang.InstantiationException e) {
596            throw new InstantiationException("Unable to instantiate fragment " + fname
597                    + ": make sure class name exists, is public, and has an"
598                    + " empty constructor that is public", e);
599        } catch (IllegalAccessException e) {
600            throw new InstantiationException("Unable to instantiate fragment " + fname
601                    + ": make sure class name exists, is public, and has an"
602                    + " empty constructor that is public", e);
603        }
604    }
605
606    final void restoreViewState(Bundle savedInstanceState) {
607        if (mSavedViewState != null) {
608            mView.restoreHierarchyState(mSavedViewState);
609            mSavedViewState = null;
610        }
611        mCalled = false;
612        onViewStateRestored(savedInstanceState);
613        if (!mCalled) {
614            throw new SuperNotCalledException("Fragment " + this
615                    + " did not call through to super.onViewStateRestored()");
616        }
617    }
618
619    final void setIndex(int index, Fragment parent) {
620        mIndex = index;
621        if (parent != null) {
622            mWho = parent.mWho + ":" + mIndex;
623        } else {
624            mWho = "android:fragment:" + mIndex;
625        }
626   }
627
628    final boolean isInBackStack() {
629        return mBackStackNesting > 0;
630    }
631
632    /**
633     * Subclasses can not override equals().
634     */
635    @Override final public boolean equals(Object o) {
636        return super.equals(o);
637    }
638
639    /**
640     * Subclasses can not override hashCode().
641     */
642    @Override final public int hashCode() {
643        return super.hashCode();
644    }
645
646    @Override
647    public String toString() {
648        StringBuilder sb = new StringBuilder(128);
649        DebugUtils.buildShortClassTag(this, sb);
650        if (mIndex >= 0) {
651            sb.append(" #");
652            sb.append(mIndex);
653        }
654        if (mFragmentId != 0) {
655            sb.append(" id=0x");
656            sb.append(Integer.toHexString(mFragmentId));
657        }
658        if (mTag != null) {
659            sb.append(" ");
660            sb.append(mTag);
661        }
662        sb.append('}');
663        return sb.toString();
664    }
665
666    /**
667     * Return the identifier this fragment is known by.  This is either
668     * the android:id value supplied in a layout or the container view ID
669     * supplied when adding the fragment.
670     */
671    final public int getId() {
672        return mFragmentId;
673    }
674
675    /**
676     * Get the tag name of the fragment, if specified.
677     */
678    final public String getTag() {
679        return mTag;
680    }
681
682    /**
683     * Supply the construction arguments for this fragment.  This can only
684     * be called before the fragment has been attached to its activity; that
685     * is, you should call it immediately after constructing the fragment.  The
686     * arguments supplied here will be retained across fragment destroy and
687     * creation.
688     */
689    public void setArguments(Bundle args) {
690        if (mIndex >= 0) {
691            throw new IllegalStateException("Fragment already active");
692        }
693        mArguments = args;
694    }
695
696    /**
697     * Return the arguments supplied when the fragment was instantiated,
698     * if any.
699     */
700    final public Bundle getArguments() {
701        return mArguments;
702    }
703
704    /**
705     * Set the initial saved state that this Fragment should restore itself
706     * from when first being constructed, as returned by
707     * {@link FragmentManager#saveFragmentInstanceState(Fragment)
708     * FragmentManager.saveFragmentInstanceState}.
709     *
710     * @param state The state the fragment should be restored from.
711     */
712    public void setInitialSavedState(SavedState state) {
713        if (mIndex >= 0) {
714            throw new IllegalStateException("Fragment already active");
715        }
716        mSavedFragmentState = state != null && state.mState != null
717                ? state.mState : null;
718    }
719
720    /**
721     * Optional target for this fragment.  This may be used, for example,
722     * if this fragment is being started by another, and when done wants to
723     * give a result back to the first.  The target set here is retained
724     * across instances via {@link FragmentManager#putFragment
725     * FragmentManager.putFragment()}.
726     *
727     * @param fragment The fragment that is the target of this one.
728     * @param requestCode Optional request code, for convenience if you
729     * are going to call back with {@link #onActivityResult(int, int, Intent)}.
730     */
731    public void setTargetFragment(Fragment fragment, int requestCode) {
732        mTarget = fragment;
733        mTargetRequestCode = requestCode;
734    }
735
736    /**
737     * Return the target fragment set by {@link #setTargetFragment}.
738     */
739    final public Fragment getTargetFragment() {
740        return mTarget;
741    }
742
743    /**
744     * Return the target request code set by {@link #setTargetFragment}.
745     */
746    final public int getTargetRequestCode() {
747        return mTargetRequestCode;
748    }
749
750    /**
751     * Return the Activity this fragment is currently associated with.
752     */
753    final public Activity getActivity() {
754        return mActivity;
755    }
756
757    /**
758     * Return <code>getActivity().getResources()</code>.
759     */
760    final public Resources getResources() {
761        if (mActivity == null) {
762            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
763        }
764        return mActivity.getResources();
765    }
766
767    /**
768     * Return a localized, styled CharSequence from the application's package's
769     * default string table.
770     *
771     * @param resId Resource id for the CharSequence text
772     */
773    public final CharSequence getText(int resId) {
774        return getResources().getText(resId);
775    }
776
777    /**
778     * Return a localized string from the application's package's
779     * default string table.
780     *
781     * @param resId Resource id for the string
782     */
783    public final String getString(int resId) {
784        return getResources().getString(resId);
785    }
786
787    /**
788     * Return a localized formatted string from the application's package's
789     * default string table, substituting the format arguments as defined in
790     * {@link java.util.Formatter} and {@link java.lang.String#format}.
791     *
792     * @param resId Resource id for the format string
793     * @param formatArgs The format arguments that will be used for substitution.
794     */
795
796    public final String getString(int resId, Object... formatArgs) {
797        return getResources().getString(resId, formatArgs);
798    }
799
800    /**
801     * Return the FragmentManager for interacting with fragments associated
802     * with this fragment's activity.  Note that this will be non-null slightly
803     * before {@link #getActivity()}, during the time from when the fragment is
804     * placed in a {@link FragmentTransaction} until it is committed and
805     * attached to its activity.
806     *
807     * <p>If this Fragment is a child of another Fragment, the FragmentManager
808     * returned here will be the parent's {@link #getChildFragmentManager()}.
809     */
810    final public FragmentManager getFragmentManager() {
811        return mFragmentManager;
812    }
813
814    /**
815     * Return a private FragmentManager for placing and managing Fragments
816     * inside of this Fragment.
817     */
818    final public FragmentManager getChildFragmentManager() {
819        if (mChildFragmentManager == null) {
820            instantiateChildFragmentManager();
821            if (mState >= RESUMED) {
822                mChildFragmentManager.dispatchResume();
823            } else if (mState >= STARTED) {
824                mChildFragmentManager.dispatchStart();
825            } else if (mState >= ACTIVITY_CREATED) {
826                mChildFragmentManager.dispatchActivityCreated();
827            } else if (mState >= CREATED) {
828                mChildFragmentManager.dispatchCreate();
829            }
830        }
831        return mChildFragmentManager;
832    }
833
834    /**
835     * Return true if the fragment is currently added to its activity.
836     */
837    final public boolean isAdded() {
838        return mActivity != null && mAdded;
839    }
840
841    /**
842     * Return true if the fragment has been explicitly detached from the UI.
843     * That is, {@link FragmentTransaction#detach(Fragment)
844     * FragmentTransaction.detach(Fragment)} has been used on it.
845     */
846    final public boolean isDetached() {
847        return mDetached;
848    }
849
850    /**
851     * Return true if this fragment is currently being removed from its
852     * activity.  This is  <em>not</em> whether its activity is finishing, but
853     * rather whether it is in the process of being removed from its activity.
854     */
855    final public boolean isRemoving() {
856        return mRemoving;
857    }
858
859    /**
860     * Return true if the layout is included as part of an activity view
861     * hierarchy via the &lt;fragment&gt; tag.  This will always be true when
862     * fragments are created through the &lt;fragment&gt; tag, <em>except</em>
863     * in the case where an old fragment is restored from a previous state and
864     * it does not appear in the layout of the current state.
865     */
866    final public boolean isInLayout() {
867        return mInLayout;
868    }
869
870    /**
871     * Return true if the fragment is in the resumed state.  This is true
872     * for the duration of {@link #onResume()} and {@link #onPause()} as well.
873     */
874    final public boolean isResumed() {
875        return mResumed;
876    }
877
878    /**
879     * Return true if the fragment is currently visible to the user.  This means
880     * it: (1) has been added, (2) has its view attached to the window, and
881     * (3) is not hidden.
882     */
883    final public boolean isVisible() {
884        return isAdded() && !isHidden() && mView != null
885                && mView.getWindowToken() != null && mView.getVisibility() == View.VISIBLE;
886    }
887
888    /**
889     * Return true if the fragment has been hidden.  By default fragments
890     * are shown.  You can find out about changes to this state with
891     * {@link #onHiddenChanged}.  Note that the hidden state is orthogonal
892     * to other states -- that is, to be visible to the user, a fragment
893     * must be both started and not hidden.
894     */
895    final public boolean isHidden() {
896        return mHidden;
897    }
898
899    /**
900     * Called when the hidden state (as returned by {@link #isHidden()} of
901     * the fragment has changed.  Fragments start out not hidden; this will
902     * be called whenever the fragment changes state from that.
903     * @param hidden True if the fragment is now hidden, false if it is not
904     * visible.
905     */
906    public void onHiddenChanged(boolean hidden) {
907    }
908
909    /**
910     * Control whether a fragment instance is retained across Activity
911     * re-creation (such as from a configuration change).  This can only
912     * be used with fragments not in the back stack.  If set, the fragment
913     * lifecycle will be slightly different when an activity is recreated:
914     * <ul>
915     * <li> {@link #onDestroy()} will not be called (but {@link #onDetach()} still
916     * will be, because the fragment is being detached from its current activity).
917     * <li> {@link #onCreate(Bundle)} will not be called since the fragment
918     * is not being re-created.
919     * <li> {@link #onAttach(Activity)} and {@link #onActivityCreated(Bundle)} <b>will</b>
920     * still be called.
921     * </ul>
922     */
923    public void setRetainInstance(boolean retain) {
924        if (retain && mParentFragment != null) {
925            throw new IllegalStateException(
926                    "Can't retain fragements that are nested in other fragments");
927        }
928        mRetainInstance = retain;
929    }
930
931    final public boolean getRetainInstance() {
932        return mRetainInstance;
933    }
934
935    /**
936     * Report that this fragment would like to participate in populating
937     * the options menu by receiving a call to {@link #onCreateOptionsMenu}
938     * and related methods.
939     *
940     * @param hasMenu If true, the fragment has menu items to contribute.
941     */
942    public void setHasOptionsMenu(boolean hasMenu) {
943        if (mHasMenu != hasMenu) {
944            mHasMenu = hasMenu;
945            if (isAdded() && !isHidden()) {
946                mFragmentManager.invalidateOptionsMenu();
947            }
948        }
949    }
950
951    /**
952     * Set a hint for whether this fragment's menu should be visible.  This
953     * is useful if you know that a fragment has been placed in your view
954     * hierarchy so that the user can not currently seen it, so any menu items
955     * it has should also not be shown.
956     *
957     * @param menuVisible The default is true, meaning the fragment's menu will
958     * be shown as usual.  If false, the user will not see the menu.
959     */
960    public void setMenuVisibility(boolean menuVisible) {
961        if (mMenuVisible != menuVisible) {
962            mMenuVisible = menuVisible;
963            if (mHasMenu && isAdded() && !isHidden()) {
964                mFragmentManager.invalidateOptionsMenu();
965            }
966        }
967    }
968
969    /**
970     * Set a hint to the system about whether this fragment's UI is currently visible
971     * to the user. This hint defaults to true and is persistent across fragment instance
972     * state save and restore.
973     *
974     * <p>An app may set this to false to indicate that the fragment's UI is
975     * scrolled out of visibility or is otherwise not directly visible to the user.
976     * This may be used by the system to prioritize operations such as fragment lifecycle updates
977     * or loader ordering behavior.</p>
978     *
979     * @param isVisibleToUser true if this fragment's UI is currently visible to the user (default),
980     *                        false if it is not.
981     */
982    public void setUserVisibleHint(boolean isVisibleToUser) {
983        if (!mUserVisibleHint && isVisibleToUser && mState < STARTED) {
984            mFragmentManager.performPendingDeferredStart(this);
985        }
986        mUserVisibleHint = isVisibleToUser;
987        mDeferStart = !isVisibleToUser;
988    }
989
990    /**
991     * @return The current value of the user-visible hint on this fragment.
992     * @see #setUserVisibleHint(boolean)
993     */
994    public boolean getUserVisibleHint() {
995        return mUserVisibleHint;
996    }
997
998    /**
999     * Return the LoaderManager for this fragment, creating it if needed.
1000     */
1001    public LoaderManager getLoaderManager() {
1002        if (mLoaderManager != null) {
1003            return mLoaderManager;
1004        }
1005        if (mActivity == null) {
1006            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1007        }
1008        mCheckedForLoaderManager = true;
1009        mLoaderManager = mActivity.getLoaderManager(mWho, mLoadersStarted, true);
1010        return mLoaderManager;
1011    }
1012
1013    /**
1014     * Call {@link Activity#startActivity(Intent)} on the fragment's
1015     * containing Activity.
1016     *
1017     * @param intent The intent to start.
1018     */
1019    public void startActivity(Intent intent) {
1020        startActivity(intent, null);
1021    }
1022
1023    /**
1024     * Call {@link Activity#startActivity(Intent, Bundle)} on the fragment's
1025     * containing Activity.
1026     *
1027     * @param intent The intent to start.
1028     * @param options Additional options for how the Activity should be started.
1029     * See {@link android.content.Context#startActivity(Intent, Bundle)
1030     * Context.startActivity(Intent, Bundle)} for more details.
1031     */
1032    public void startActivity(Intent intent, Bundle options) {
1033        if (mActivity == null) {
1034            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1035        }
1036        if (options != null) {
1037            mActivity.startActivityFromFragment(this, intent, -1, options);
1038        } else {
1039            // Note we want to go through this call for compatibility with
1040            // applications that may have overridden the method.
1041            mActivity.startActivityFromFragment(this, intent, -1);
1042        }
1043    }
1044
1045    /**
1046     * Call {@link Activity#startActivityForResult(Intent, int)} on the fragment's
1047     * containing Activity.
1048     */
1049    public void startActivityForResult(Intent intent, int requestCode) {
1050        startActivityForResult(intent, requestCode, null);
1051    }
1052
1053    /**
1054     * Call {@link Activity#startActivityForResult(Intent, int, Bundle)} on the fragment's
1055     * containing Activity.
1056     */
1057    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
1058        if (mActivity == null) {
1059            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1060        }
1061        if (options != null) {
1062            mActivity.startActivityFromFragment(this, intent, requestCode, options);
1063        } else {
1064            // Note we want to go through this call for compatibility with
1065            // applications that may have overridden the method.
1066            mActivity.startActivityFromFragment(this, intent, requestCode, options);
1067        }
1068    }
1069
1070    /**
1071     * Receive the result from a previous call to
1072     * {@link #startActivityForResult(Intent, int)}.  This follows the
1073     * related Activity API as described there in
1074     * {@link Activity#onActivityResult(int, int, Intent)}.
1075     *
1076     * @param requestCode The integer request code originally supplied to
1077     *                    startActivityForResult(), allowing you to identify who this
1078     *                    result came from.
1079     * @param resultCode The integer result code returned by the child activity
1080     *                   through its setResult().
1081     * @param data An Intent, which can return result data to the caller
1082     *               (various data can be attached to Intent "extras").
1083     */
1084    public void onActivityResult(int requestCode, int resultCode, Intent data) {
1085    }
1086
1087    /**
1088     * @hide Hack so that DialogFragment can make its Dialog before creating
1089     * its views, and the view construction can use the dialog's context for
1090     * inflation.  Maybe this should become a public API. Note sure.
1091     */
1092    public LayoutInflater getLayoutInflater(Bundle savedInstanceState) {
1093        return mActivity.getLayoutInflater();
1094    }
1095
1096    /**
1097     * @deprecated Use {@link #onInflate(Activity, AttributeSet, Bundle)} instead.
1098     */
1099    @Deprecated
1100    public void onInflate(AttributeSet attrs, Bundle savedInstanceState) {
1101        mCalled = true;
1102    }
1103
1104    /**
1105     * Called when a fragment is being created as part of a view layout
1106     * inflation, typically from setting the content view of an activity.  This
1107     * may be called immediately after the fragment is created from a <fragment>
1108     * tag in a layout file.  Note this is <em>before</em> the fragment's
1109     * {@link #onAttach(Activity)} has been called; all you should do here is
1110     * parse the attributes and save them away.
1111     *
1112     * <p>This is called every time the fragment is inflated, even if it is
1113     * being inflated into a new instance with saved state.  It typically makes
1114     * sense to re-parse the parameters each time, to allow them to change with
1115     * different configurations.</p>
1116     *
1117     * <p>Here is a typical implementation of a fragment that can take parameters
1118     * both through attributes supplied here as well from {@link #getArguments()}:</p>
1119     *
1120     * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
1121     *      fragment}
1122     *
1123     * <p>Note that parsing the XML attributes uses a "styleable" resource.  The
1124     * declaration for the styleable used here is:</p>
1125     *
1126     * {@sample development/samples/ApiDemos/res/values/attrs.xml fragment_arguments}
1127     *
1128     * <p>The fragment can then be declared within its activity's content layout
1129     * through a tag like this:</p>
1130     *
1131     * {@sample development/samples/ApiDemos/res/layout/fragment_arguments.xml from_attributes}
1132     *
1133     * <p>This fragment can also be created dynamically from arguments given
1134     * at runtime in the arguments Bundle; here is an example of doing so at
1135     * creation of the containing activity:</p>
1136     *
1137     * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
1138     *      create}
1139     *
1140     * @param activity The Activity that is inflating this fragment.
1141     * @param attrs The attributes at the tag where the fragment is
1142     * being created.
1143     * @param savedInstanceState If the fragment is being re-created from
1144     * a previous saved state, this is the state.
1145     */
1146    public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
1147        onInflate(attrs, savedInstanceState);
1148        mCalled = true;
1149    }
1150
1151    /**
1152     * Called when a fragment is first attached to its activity.
1153     * {@link #onCreate(Bundle)} will be called after this.
1154     */
1155    public void onAttach(Activity activity) {
1156        mCalled = true;
1157    }
1158
1159    /**
1160     * Called when a fragment loads an animation.
1161     */
1162    public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) {
1163        return null;
1164    }
1165
1166    /**
1167     * Called to do initial creation of a fragment.  This is called after
1168     * {@link #onAttach(Activity)} and before
1169     * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
1170     *
1171     * <p>Note that this can be called while the fragment's activity is
1172     * still in the process of being created.  As such, you can not rely
1173     * on things like the activity's content view hierarchy being initialized
1174     * at this point.  If you want to do work once the activity itself is
1175     * created, see {@link #onActivityCreated(Bundle)}.
1176     *
1177     * @param savedInstanceState If the fragment is being re-created from
1178     * a previous saved state, this is the state.
1179     */
1180    public void onCreate(Bundle savedInstanceState) {
1181        mCalled = true;
1182    }
1183
1184    /**
1185     * Called immediately after {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}
1186     * has returned, but before any saved state has been restored in to the view.
1187     * This gives subclasses a chance to initialize themselves once
1188     * they know their view hierarchy has been completely created.  The fragment's
1189     * view hierarchy is not however attached to its parent at this point.
1190     * @param view The View returned by {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
1191     * @param savedInstanceState If non-null, this fragment is being re-constructed
1192     * from a previous saved state as given here.
1193     */
1194    public void onViewCreated(View view, Bundle savedInstanceState) {
1195    }
1196
1197    /**
1198     * Called to have the fragment instantiate its user interface view.
1199     * This is optional, and non-graphical fragments can return null (which
1200     * is the default implementation).  This will be called between
1201     * {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}.
1202     *
1203     * <p>If you return a View from here, you will later be called in
1204     * {@link #onDestroyView} when the view is being released.
1205     *
1206     * @param inflater The LayoutInflater object that can be used to inflate
1207     * any views in the fragment,
1208     * @param container If non-null, this is the parent view that the fragment's
1209     * UI should be attached to.  The fragment should not add the view itself,
1210     * but this can be used to generate the LayoutParams of the view.
1211     * @param savedInstanceState If non-null, this fragment is being re-constructed
1212     * from a previous saved state as given here.
1213     *
1214     * @return Return the View for the fragment's UI, or null.
1215     */
1216    public View onCreateView(LayoutInflater inflater, ViewGroup container,
1217            Bundle savedInstanceState) {
1218        return null;
1219    }
1220
1221    /**
1222     * Get the root view for the fragment's layout (the one returned by {@link #onCreateView}),
1223     * if provided.
1224     *
1225     * @return The fragment's root view, or null if it has no layout.
1226     */
1227    public View getView() {
1228        return mView;
1229    }
1230
1231    /**
1232     * Called when the fragment's activity has been created and this
1233     * fragment's view hierarchy instantiated.  It can be used to do final
1234     * initialization once these pieces are in place, such as retrieving
1235     * views or restoring state.  It is also useful for fragments that use
1236     * {@link #setRetainInstance(boolean)} to retain their instance,
1237     * as this callback tells the fragment when it is fully associated with
1238     * the new activity instance.  This is called after {@link #onCreateView}
1239     * and before {@link #onViewStateRestored(Bundle)}.
1240     *
1241     * @param savedInstanceState If the fragment is being re-created from
1242     * a previous saved state, this is the state.
1243     */
1244    public void onActivityCreated(Bundle savedInstanceState) {
1245        mCalled = true;
1246    }
1247
1248    /**
1249     * Called when all saved state has been restored into the view hierarchy
1250     * of the fragment.  This can be used to do initialization based on saved
1251     * state that you are letting the view hierarchy track itself, such as
1252     * whether check box widgets are currently checked.  This is called
1253     * after {@link #onActivityCreated(Bundle)} and before
1254     * {@link #onStart()}.
1255     *
1256     * @param savedInstanceState If the fragment is being re-created from
1257     * a previous saved state, this is the state.
1258     */
1259    public void onViewStateRestored(Bundle savedInstanceState) {
1260        mCalled = true;
1261    }
1262
1263    /**
1264     * Called when the Fragment is visible to the user.  This is generally
1265     * tied to {@link Activity#onStart() Activity.onStart} of the containing
1266     * Activity's lifecycle.
1267     */
1268    public void onStart() {
1269        mCalled = true;
1270
1271        if (!mLoadersStarted) {
1272            mLoadersStarted = true;
1273            if (!mCheckedForLoaderManager) {
1274                mCheckedForLoaderManager = true;
1275                mLoaderManager = mActivity.getLoaderManager(mWho, mLoadersStarted, false);
1276            }
1277            if (mLoaderManager != null) {
1278                mLoaderManager.doStart();
1279            }
1280        }
1281    }
1282
1283    /**
1284     * Called when the fragment is visible to the user and actively running.
1285     * This is generally
1286     * tied to {@link Activity#onResume() Activity.onResume} of the containing
1287     * Activity's lifecycle.
1288     */
1289    public void onResume() {
1290        mCalled = true;
1291    }
1292
1293    /**
1294     * Called to ask the fragment to save its current dynamic state, so it
1295     * can later be reconstructed in a new instance of its process is
1296     * restarted.  If a new instance of the fragment later needs to be
1297     * created, the data you place in the Bundle here will be available
1298     * in the Bundle given to {@link #onCreate(Bundle)},
1299     * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}, and
1300     * {@link #onActivityCreated(Bundle)}.
1301     *
1302     * <p>This corresponds to {@link Activity#onSaveInstanceState(Bundle)
1303     * Activity.onSaveInstanceState(Bundle)} and most of the discussion there
1304     * applies here as well.  Note however: <em>this method may be called
1305     * at any time before {@link #onDestroy()}</em>.  There are many situations
1306     * where a fragment may be mostly torn down (such as when placed on the
1307     * back stack with no UI showing), but its state will not be saved until
1308     * its owning activity actually needs to save its state.
1309     *
1310     * @param outState Bundle in which to place your saved state.
1311     */
1312    public void onSaveInstanceState(Bundle outState) {
1313    }
1314
1315    public void onConfigurationChanged(Configuration newConfig) {
1316        mCalled = true;
1317    }
1318
1319    /**
1320     * Called when the Fragment is no longer resumed.  This is generally
1321     * tied to {@link Activity#onPause() Activity.onPause} of the containing
1322     * Activity's lifecycle.
1323     */
1324    public void onPause() {
1325        mCalled = true;
1326    }
1327
1328    /**
1329     * Called when the Fragment is no longer started.  This is generally
1330     * tied to {@link Activity#onStop() Activity.onStop} of the containing
1331     * Activity's lifecycle.
1332     */
1333    public void onStop() {
1334        mCalled = true;
1335    }
1336
1337    public void onLowMemory() {
1338        mCalled = true;
1339    }
1340
1341    public void onTrimMemory(int level) {
1342        mCalled = true;
1343    }
1344
1345    /**
1346     * Called when the view previously created by {@link #onCreateView} has
1347     * been detached from the fragment.  The next time the fragment needs
1348     * to be displayed, a new view will be created.  This is called
1349     * after {@link #onStop()} and before {@link #onDestroy()}.  It is called
1350     * <em>regardless</em> of whether {@link #onCreateView} returned a
1351     * non-null view.  Internally it is called after the view's state has
1352     * been saved but before it has been removed from its parent.
1353     */
1354    public void onDestroyView() {
1355        mCalled = true;
1356    }
1357
1358    /**
1359     * Called when the fragment is no longer in use.  This is called
1360     * after {@link #onStop()} and before {@link #onDetach()}.
1361     */
1362    public void onDestroy() {
1363        mCalled = true;
1364        //Log.v("foo", "onDestroy: mCheckedForLoaderManager=" + mCheckedForLoaderManager
1365        //        + " mLoaderManager=" + mLoaderManager);
1366        if (!mCheckedForLoaderManager) {
1367            mCheckedForLoaderManager = true;
1368            mLoaderManager = mActivity.getLoaderManager(mWho, mLoadersStarted, false);
1369        }
1370        if (mLoaderManager != null) {
1371            mLoaderManager.doDestroy();
1372        }
1373    }
1374
1375    /**
1376     * Called by the fragment manager once this fragment has been removed,
1377     * so that we don't have any left-over state if the application decides
1378     * to re-use the instance.  This only clears state that the framework
1379     * internally manages, not things the application sets.
1380     */
1381    void initState() {
1382        mIndex = -1;
1383        mWho = null;
1384        mAdded = false;
1385        mRemoving = false;
1386        mResumed = false;
1387        mFromLayout = false;
1388        mInLayout = false;
1389        mRestored = false;
1390        mBackStackNesting = 0;
1391        mFragmentManager = null;
1392        mActivity = null;
1393        mFragmentId = 0;
1394        mContainerId = 0;
1395        mTag = null;
1396        mHidden = false;
1397        mDetached = false;
1398        mRetaining = false;
1399        mLoaderManager = null;
1400        mLoadersStarted = false;
1401        mCheckedForLoaderManager = false;
1402    }
1403
1404    /**
1405     * Called when the fragment is no longer attached to its activity.  This
1406     * is called after {@link #onDestroy()}.
1407     */
1408    public void onDetach() {
1409        mCalled = true;
1410    }
1411
1412    /**
1413     * Initialize the contents of the Activity's standard options menu.  You
1414     * should place your menu items in to <var>menu</var>.  For this method
1415     * to be called, you must have first called {@link #setHasOptionsMenu}.  See
1416     * {@link Activity#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu}
1417     * for more information.
1418     *
1419     * @param menu The options menu in which you place your items.
1420     *
1421     * @see #setHasOptionsMenu
1422     * @see #onPrepareOptionsMenu
1423     * @see #onOptionsItemSelected
1424     */
1425    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
1426    }
1427
1428    /**
1429     * Prepare the Screen's standard options menu to be displayed.  This is
1430     * called right before the menu is shown, every time it is shown.  You can
1431     * use this method to efficiently enable/disable items or otherwise
1432     * dynamically modify the contents.  See
1433     * {@link Activity#onPrepareOptionsMenu(Menu) Activity.onPrepareOptionsMenu}
1434     * for more information.
1435     *
1436     * @param menu The options menu as last shown or first initialized by
1437     *             onCreateOptionsMenu().
1438     *
1439     * @see #setHasOptionsMenu
1440     * @see #onCreateOptionsMenu
1441     */
1442    public void onPrepareOptionsMenu(Menu menu) {
1443    }
1444
1445    /**
1446     * Called when this fragment's option menu items are no longer being
1447     * included in the overall options menu.  Receiving this call means that
1448     * the menu needed to be rebuilt, but this fragment's items were not
1449     * included in the newly built menu (its {@link #onCreateOptionsMenu(Menu, MenuInflater)}
1450     * was not called).
1451     */
1452    public void onDestroyOptionsMenu() {
1453    }
1454
1455    /**
1456     * This hook is called whenever an item in your options menu is selected.
1457     * The default implementation simply returns false to have the normal
1458     * processing happen (calling the item's Runnable or sending a message to
1459     * its Handler as appropriate).  You can use this method for any items
1460     * for which you would like to do processing without those other
1461     * facilities.
1462     *
1463     * <p>Derived classes should call through to the base class for it to
1464     * perform the default menu handling.
1465     *
1466     * @param item The menu item that was selected.
1467     *
1468     * @return boolean Return false to allow normal menu processing to
1469     *         proceed, true to consume it here.
1470     *
1471     * @see #onCreateOptionsMenu
1472     */
1473    public boolean onOptionsItemSelected(MenuItem item) {
1474        return false;
1475    }
1476
1477    /**
1478     * This hook is called whenever the options menu is being closed (either by the user canceling
1479     * the menu with the back/menu button, or when an item is selected).
1480     *
1481     * @param menu The options menu as last shown or first initialized by
1482     *             onCreateOptionsMenu().
1483     */
1484    public void onOptionsMenuClosed(Menu menu) {
1485    }
1486
1487    /**
1488     * Called when a context menu for the {@code view} is about to be shown.
1489     * Unlike {@link #onCreateOptionsMenu}, this will be called every
1490     * time the context menu is about to be shown and should be populated for
1491     * the view (or item inside the view for {@link AdapterView} subclasses,
1492     * this can be found in the {@code menuInfo})).
1493     * <p>
1494     * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
1495     * item has been selected.
1496     * <p>
1497     * The default implementation calls up to
1498     * {@link Activity#onCreateContextMenu Activity.onCreateContextMenu}, though
1499     * you can not call this implementation if you don't want that behavior.
1500     * <p>
1501     * It is not safe to hold onto the context menu after this method returns.
1502     * {@inheritDoc}
1503     */
1504    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1505        getActivity().onCreateContextMenu(menu, v, menuInfo);
1506    }
1507
1508    /**
1509     * Registers a context menu to be shown for the given view (multiple views
1510     * can show the context menu). This method will set the
1511     * {@link OnCreateContextMenuListener} on the view to this fragment, so
1512     * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
1513     * called when it is time to show the context menu.
1514     *
1515     * @see #unregisterForContextMenu(View)
1516     * @param view The view that should show a context menu.
1517     */
1518    public void registerForContextMenu(View view) {
1519        view.setOnCreateContextMenuListener(this);
1520    }
1521
1522    /**
1523     * Prevents a context menu to be shown for the given view. This method will
1524     * remove the {@link OnCreateContextMenuListener} on the view.
1525     *
1526     * @see #registerForContextMenu(View)
1527     * @param view The view that should stop showing a context menu.
1528     */
1529    public void unregisterForContextMenu(View view) {
1530        view.setOnCreateContextMenuListener(null);
1531    }
1532
1533    /**
1534     * This hook is called whenever an item in a context menu is selected. The
1535     * default implementation simply returns false to have the normal processing
1536     * happen (calling the item's Runnable or sending a message to its Handler
1537     * as appropriate). You can use this method for any items for which you
1538     * would like to do processing without those other facilities.
1539     * <p>
1540     * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
1541     * View that added this menu item.
1542     * <p>
1543     * Derived classes should call through to the base class for it to perform
1544     * the default menu handling.
1545     *
1546     * @param item The context menu item that was selected.
1547     * @return boolean Return false to allow normal context menu processing to
1548     *         proceed, true to consume it here.
1549     */
1550    public boolean onContextItemSelected(MenuItem item) {
1551        return false;
1552    }
1553
1554    /**
1555     * Print the Fragments's state into the given stream.
1556     *
1557     * @param prefix Text to print at the front of each line.
1558     * @param fd The raw file descriptor that the dump is being sent to.
1559     * @param writer The PrintWriter to which you should dump your state.  This will be
1560     * closed for you after you return.
1561     * @param args additional arguments to the dump request.
1562     */
1563    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
1564        writer.print(prefix); writer.print("mFragmentId=#");
1565                writer.print(Integer.toHexString(mFragmentId));
1566                writer.print(" mContainerId=#");
1567                writer.print(Integer.toHexString(mContainerId));
1568                writer.print(" mTag="); writer.println(mTag);
1569        writer.print(prefix); writer.print("mState="); writer.print(mState);
1570                writer.print(" mIndex="); writer.print(mIndex);
1571                writer.print(" mWho="); writer.print(mWho);
1572                writer.print(" mBackStackNesting="); writer.println(mBackStackNesting);
1573        writer.print(prefix); writer.print("mAdded="); writer.print(mAdded);
1574                writer.print(" mRemoving="); writer.print(mRemoving);
1575                writer.print(" mResumed="); writer.print(mResumed);
1576                writer.print(" mFromLayout="); writer.print(mFromLayout);
1577                writer.print(" mInLayout="); writer.println(mInLayout);
1578        writer.print(prefix); writer.print("mHidden="); writer.print(mHidden);
1579                writer.print(" mDetached="); writer.print(mDetached);
1580                writer.print(" mMenuVisible="); writer.print(mMenuVisible);
1581                writer.print(" mHasMenu="); writer.println(mHasMenu);
1582        writer.print(prefix); writer.print("mRetainInstance="); writer.print(mRetainInstance);
1583                writer.print(" mRetaining="); writer.print(mRetaining);
1584                writer.print(" mUserVisibleHint="); writer.println(mUserVisibleHint);
1585        if (mFragmentManager != null) {
1586            writer.print(prefix); writer.print("mFragmentManager=");
1587                    writer.println(mFragmentManager);
1588        }
1589        if (mActivity != null) {
1590            writer.print(prefix); writer.print("mActivity=");
1591                    writer.println(mActivity);
1592        }
1593        if (mChildFragmentManager != null) {
1594            writer.print(prefix); writer.print("mChildFragmentManager=");
1595                    writer.println(mChildFragmentManager);
1596        }
1597        if (mParentFragment != null) {
1598            writer.print(prefix); writer.print("mParentFragment=");
1599                    writer.println(mParentFragment);
1600        }
1601        if (mArguments != null) {
1602            writer.print(prefix); writer.print("mArguments="); writer.println(mArguments);
1603        }
1604        if (mSavedFragmentState != null) {
1605            writer.print(prefix); writer.print("mSavedFragmentState=");
1606                    writer.println(mSavedFragmentState);
1607        }
1608        if (mSavedViewState != null) {
1609            writer.print(prefix); writer.print("mSavedViewState=");
1610                    writer.println(mSavedViewState);
1611        }
1612        if (mTarget != null) {
1613            writer.print(prefix); writer.print("mTarget="); writer.print(mTarget);
1614                    writer.print(" mTargetRequestCode=");
1615                    writer.println(mTargetRequestCode);
1616        }
1617        if (mNextAnim != 0) {
1618            writer.print(prefix); writer.print("mNextAnim="); writer.println(mNextAnim);
1619        }
1620        if (mContainer != null) {
1621            writer.print(prefix); writer.print("mContainer="); writer.println(mContainer);
1622        }
1623        if (mView != null) {
1624            writer.print(prefix); writer.print("mView="); writer.println(mView);
1625        }
1626        if (mAnimatingAway != null) {
1627            writer.print(prefix); writer.print("mAnimatingAway="); writer.println(mAnimatingAway);
1628            writer.print(prefix); writer.print("mStateAfterAnimating=");
1629                    writer.println(mStateAfterAnimating);
1630        }
1631        if (mLoaderManager != null) {
1632            writer.print(prefix); writer.println("Loader Manager:");
1633            mLoaderManager.dump(prefix + "  ", fd, writer, args);
1634        }
1635        if (mChildFragmentManager != null) {
1636            writer.print(prefix); writer.println("Child Fragment Manager:");
1637            mChildFragmentManager.dump(prefix + "  ", fd, writer, args);
1638        }
1639    }
1640
1641    Fragment findFragmentByWho(String who) {
1642        if (who.equals(mWho)) {
1643            return this;
1644        }
1645        if (mChildFragmentManager != null) {
1646            return mChildFragmentManager.findFragmentByWho(who);
1647        }
1648        return null;
1649    }
1650
1651    void instantiateChildFragmentManager() {
1652        mChildFragmentManager = new FragmentManagerImpl();
1653        mChildFragmentManager.attachActivity(mActivity, new FragmentContainer() {
1654            @Override
1655            public View findViewById(int id) {
1656                if (mView == null) {
1657                    throw new IllegalStateException("Fragment does not have a view");
1658                }
1659                return mView.findViewById(id);
1660            }
1661        }, this);
1662    }
1663
1664    void performCreate(Bundle savedInstanceState) {
1665        mCalled = false;
1666        onCreate(savedInstanceState);
1667        if (!mCalled) {
1668            throw new SuperNotCalledException("Fragment " + this
1669                    + " did not call through to super.onCreate()");
1670        }
1671        if (savedInstanceState != null) {
1672            Parcelable p = savedInstanceState.getParcelable(Activity.FRAGMENTS_TAG);
1673            if (p != null) {
1674                if (mChildFragmentManager == null) {
1675                    instantiateChildFragmentManager();
1676                }
1677                mChildFragmentManager.restoreAllState(p, null);
1678                mChildFragmentManager.dispatchCreate();
1679            }
1680        }
1681    }
1682
1683    void performActivityCreated(Bundle savedInstanceState) {
1684        mCalled = false;
1685        onActivityCreated(savedInstanceState);
1686        if (!mCalled) {
1687            throw new SuperNotCalledException("Fragment " + this
1688                    + " did not call through to super.onActivityCreated()");
1689        }
1690        if (mChildFragmentManager != null) {
1691            mChildFragmentManager.dispatchActivityCreated();
1692        }
1693    }
1694
1695    void performStart() {
1696        if (mChildFragmentManager != null) {
1697            mChildFragmentManager.noteStateNotSaved();
1698            mChildFragmentManager.execPendingActions();
1699        }
1700        mCalled = false;
1701        onStart();
1702        if (!mCalled) {
1703            throw new SuperNotCalledException("Fragment " + this
1704                    + " did not call through to super.onStart()");
1705        }
1706        if (mChildFragmentManager != null) {
1707            mChildFragmentManager.dispatchStart();
1708        }
1709        if (mLoaderManager != null) {
1710            mLoaderManager.doReportStart();
1711        }
1712    }
1713
1714    void performResume() {
1715        if (mChildFragmentManager != null) {
1716            mChildFragmentManager.execPendingActions();
1717        }
1718        mCalled = false;
1719        onResume();
1720        if (!mCalled) {
1721            throw new SuperNotCalledException("Fragment " + this
1722                    + " did not call through to super.onResume()");
1723        }
1724        if (mChildFragmentManager != null) {
1725            mChildFragmentManager.dispatchResume();
1726            mChildFragmentManager.execPendingActions();
1727        }
1728    }
1729
1730    void performConfigurationChanged(Configuration newConfig) {
1731        onConfigurationChanged(newConfig);
1732        if (mChildFragmentManager != null) {
1733            mChildFragmentManager.dispatchConfigurationChanged(newConfig);
1734        }
1735    }
1736
1737    void performLowMemory() {
1738        onLowMemory();
1739        if (mChildFragmentManager != null) {
1740            mChildFragmentManager.dispatchLowMemory();
1741        }
1742    }
1743
1744    void performTrimMemory(int level) {
1745        onTrimMemory(level);
1746        if (mChildFragmentManager != null) {
1747            mChildFragmentManager.dispatchTrimMemory(level);
1748        }
1749    }
1750
1751    boolean performCreateOptionsMenu(Menu menu, MenuInflater inflater) {
1752        boolean show = false;
1753        if (!mHidden) {
1754            if (mHasMenu && mMenuVisible) {
1755                show = true;
1756                onCreateOptionsMenu(menu, inflater);
1757            }
1758            if (mChildFragmentManager != null) {
1759                show |= mChildFragmentManager.dispatchCreateOptionsMenu(menu, inflater);
1760            }
1761        }
1762        return show;
1763    }
1764
1765    boolean performPrepareOptionsMenu(Menu menu) {
1766        boolean show = false;
1767        if (!mHidden) {
1768            if (mHasMenu && mMenuVisible) {
1769                show = true;
1770                onPrepareOptionsMenu(menu);
1771            }
1772            if (mChildFragmentManager != null) {
1773                show |= mChildFragmentManager.dispatchPrepareOptionsMenu(menu);
1774            }
1775        }
1776        return show;
1777    }
1778
1779    boolean performOptionsItemSelected(MenuItem item) {
1780        if (!mHidden) {
1781            if (mHasMenu && mMenuVisible) {
1782                if (onOptionsItemSelected(item)) {
1783                    return true;
1784                }
1785            }
1786            if (mChildFragmentManager != null) {
1787                if (mChildFragmentManager.dispatchOptionsItemSelected(item)) {
1788                    return true;
1789                }
1790            }
1791        }
1792        return false;
1793    }
1794
1795    boolean performContextItemSelected(MenuItem item) {
1796        if (!mHidden) {
1797            if (onContextItemSelected(item)) {
1798                return true;
1799            }
1800            if (mChildFragmentManager != null) {
1801                if (mChildFragmentManager.dispatchContextItemSelected(item)) {
1802                    return true;
1803                }
1804            }
1805        }
1806        return false;
1807    }
1808
1809    void performOptionsMenuClosed(Menu menu) {
1810        if (!mHidden) {
1811            if (mHasMenu && mMenuVisible) {
1812                onOptionsMenuClosed(menu);
1813            }
1814            if (mChildFragmentManager != null) {
1815                mChildFragmentManager.dispatchOptionsMenuClosed(menu);
1816            }
1817        }
1818    }
1819
1820    void performSaveInstanceState(Bundle outState) {
1821        onSaveInstanceState(outState);
1822        if (mChildFragmentManager != null) {
1823            Parcelable p = mChildFragmentManager.saveAllState();
1824            if (p != null) {
1825                outState.putParcelable(Activity.FRAGMENTS_TAG, p);
1826            }
1827        }
1828    }
1829
1830    void performPause() {
1831        if (mChildFragmentManager != null) {
1832            mChildFragmentManager.dispatchPause();
1833        }
1834        mCalled = false;
1835        onPause();
1836        if (!mCalled) {
1837            throw new SuperNotCalledException("Fragment " + this
1838                    + " did not call through to super.onPause()");
1839        }
1840    }
1841
1842    void performStop() {
1843        if (mChildFragmentManager != null) {
1844            mChildFragmentManager.dispatchStop();
1845        }
1846        mCalled = false;
1847        onStop();
1848        if (!mCalled) {
1849            throw new SuperNotCalledException("Fragment " + this
1850                    + " did not call through to super.onStop()");
1851        }
1852
1853        if (mLoadersStarted) {
1854            mLoadersStarted = false;
1855            if (!mCheckedForLoaderManager) {
1856                mCheckedForLoaderManager = true;
1857                mLoaderManager = mActivity.getLoaderManager(mWho, mLoadersStarted, false);
1858            }
1859            if (mLoaderManager != null) {
1860                if (mActivity == null || !mActivity.mChangingConfigurations) {
1861                    mLoaderManager.doStop();
1862                } else {
1863                    mLoaderManager.doRetain();
1864                }
1865            }
1866        }
1867    }
1868
1869    void performDestroyView() {
1870        if (mChildFragmentManager != null) {
1871            mChildFragmentManager.dispatchDestroyView();
1872        }
1873        mCalled = false;
1874        onDestroyView();
1875        if (!mCalled) {
1876            throw new SuperNotCalledException("Fragment " + this
1877                    + " did not call through to super.onDestroyView()");
1878        }
1879        if (mLoaderManager != null) {
1880            mLoaderManager.doReportNextStart();
1881        }
1882    }
1883
1884    void performDestroy() {
1885        if (mChildFragmentManager != null) {
1886            mChildFragmentManager.dispatchDestroy();
1887        }
1888        mCalled = false;
1889        onDestroy();
1890        if (!mCalled) {
1891            throw new SuperNotCalledException("Fragment " + this
1892                    + " did not call through to super.onDestroy()");
1893        }
1894    }
1895}
1896