Fragment.java revision 03fcc333cf0fbbc4df1215649746d6360801efd8
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) {
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);
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 #onStart} makes the fragment visible to the user (based on its
211 * containing activity being started).
212 * <li> {@link #onResume} makes the fragment interacting with the user (based on its
213 * containing activity being resumed).
214 * </ol>
215 *
216 * <p>As a fragment is no longer being used, it goes through a reverse
217 * series of callbacks:
218 *
219 * <ol>
220 * <li> {@link #onPause} fragment is no longer interacting with the user either
221 * because its activity is being paused or a fragment operation is modifying it
222 * in the activity.
223 * <li> {@link #onStop} fragment is no longer visible to the user either
224 * because its activity is being stopped or a fragment operation is modifying it
225 * in the activity.
226 * <li> {@link #onDestroyView} allows the fragment to clean up resources
227 * associated with its View.
228 * <li> {@link #onDestroy} called to do final cleanup of the fragment's state.
229 * <li> {@link #onDetach} called immediately prior to the fragment no longer
230 * being associated with its activity.
231 * </ol>
232 *
233 * <a name="Layout"></a>
234 * <h3>Layout</h3>
235 *
236 * <p>Fragments can be used as part of your application's layout, allowing
237 * you to better modularize your code and more easily adjust your user
238 * interface to the screen it is running on.  As an example, we can look
239 * at a simple program consisting of a list of items, and display of the
240 * details of each item.</p>
241 *
242 * <p>An activity's layout XML can include <code>&lt;fragment&gt;</code> tags
243 * to embed fragment instances inside of the layout.  For example, here is
244 * a simple layout that embeds one fragment:</p>
245 *
246 * {@sample development/samples/ApiDemos/res/layout/fragment_layout.xml layout}
247 *
248 * <p>The layout is installed in the activity in the normal way:</p>
249 *
250 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
251 *      main}
252 *
253 * <p>The titles fragment, showing a list of titles, is fairly simple, relying
254 * on {@link ListFragment} for most of its work.  Note the implementation of
255 * clicking an item: depending on the current activity's layout, it can either
256 * create and display a new fragment to show the details in-place (more about
257 * this later), or start a new activity to show the details.</p>
258 *
259 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
260 *      titles}
261 *
262 * <p>The details fragment showing the contents of a selected item just
263 * displays a string of text based on an index of a string array built in to
264 * the app:</p>
265 *
266 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
267 *      details}
268 *
269 * <p>In this case when the user clicks on a title, there is no details
270 * container in the current activity, so the titles fragment's click code will
271 * launch a new activity to display the details fragment:</p>
272 *
273 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
274 *      details_activity}
275 *
276 * <p>However the screen may be large enough to show both the list of titles
277 * and details about the currently selected title.  To use such a layout on
278 * a landscape screen, this alternative layout can be placed under layout-land:</p>
279 *
280 * {@sample development/samples/ApiDemos/res/layout-land/fragment_layout.xml layout}
281 *
282 * <p>Note how the prior code will adjust to this alternative UI flow: the titles
283 * fragment will now embed the details fragment inside of this activity, and the
284 * details activity will finish itself if it is running in a configuration
285 * where the details can be shown in-place.
286 *
287 * <p>When a configuration change causes the activity hosting these fragments
288 * to restart, its new instance may use a different layout that doesn't
289 * include the same fragments as the previous layout.  In this case all of
290 * the previous fragments will still be instantiated and running in the new
291 * instance.  However, any that are no longer associated with a &lt;fragment&gt;
292 * tag in the view hierarchy will not have their content view created
293 * and will return false from {@link #isInLayout}.  (The code here also shows
294 * how you can determine if a fragment placed in a container is no longer
295 * running in a layout with that container and avoid creating its view hierarchy
296 * in that case.)
297 *
298 * <p>The attributes of the &lt;fragment&gt; tag are used to control the
299 * LayoutParams provided when attaching the fragment's view to the parent
300 * container.  They can also be parsed by the fragment in {@link #onInflate}
301 * as parameters.
302 *
303 * <p>The fragment being instantiated must have some kind of unique identifier
304 * so that it can be re-associated with a previous instance if the parent
305 * activity needs to be destroyed and recreated.  This can be provided these
306 * ways:
307 *
308 * <ul>
309 * <li>If nothing is explicitly supplied, the view ID of the container will
310 * be used.
311 * <li><code>android:tag</code> can be used in &lt;fragment&gt; to provide
312 * a specific tag name for the fragment.
313 * <li><code>android:id</code> can be used in &lt;fragment&gt; to provide
314 * a specific identifier for the fragment.
315 * </ul>
316 *
317 * <a name="BackStack"></a>
318 * <h3>Back Stack</h3>
319 *
320 * <p>The transaction in which fragments are modified can be placed on an
321 * internal back-stack of the owning activity.  When the user presses back
322 * in the activity, any transactions on the back stack are popped off before
323 * the activity itself is finished.
324 *
325 * <p>For example, consider this simple fragment that is instantiated with
326 * an integer argument and displays that in a TextView in its UI:</p>
327 *
328 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentStack.java
329 *      fragment}
330 *
331 * <p>A function that creates a new instance of the fragment, replacing
332 * whatever current fragment instance is being shown and pushing that change
333 * on to the back stack could be written as:
334 *
335 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentStack.java
336 *      add_stack}
337 *
338 * <p>After each call to this function, a new entry is on the stack, and
339 * pressing back will pop it to return the user to whatever previous state
340 * the activity UI was in.
341 */
342public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListener {
343    private static final HashMap<String, Class<?>> sClassMap =
344            new HashMap<String, Class<?>>();
345
346    static final int INVALID_STATE = -1;   // Invalid state used as a null value.
347    static final int INITIALIZING = 0;     // Not yet created.
348    static final int CREATED = 1;          // Created.
349    static final int ACTIVITY_CREATED = 2; // The activity has finished its creation.
350    static final int STOPPED = 3;          // Fully created, not started.
351    static final int STARTED = 4;          // Created and started, not resumed.
352    static final int RESUMED = 5;          // Created started and resumed.
353
354    int mState = INITIALIZING;
355
356    // Non-null if the fragment's view hierarchy is currently animating away,
357    // meaning we need to wait a bit on completely destroying it.  This is the
358    // animation that is running.
359    Animator mAnimatingAway;
360
361    // If mAnimatingAway != null, this is the state we should move to once the
362    // animation is done.
363    int mStateAfterAnimating;
364
365    // When instantiated from saved state, this is the saved state.
366    Bundle mSavedFragmentState;
367    SparseArray<Parcelable> mSavedViewState;
368
369    // Index into active fragment array.
370    int mIndex = -1;
371
372    // Internal unique name for this fragment;
373    String mWho;
374
375    // Construction arguments;
376    Bundle mArguments;
377
378    // Target fragment.
379    Fragment mTarget;
380
381    // For use when retaining a fragment: this is the index of the last mTarget.
382    int mTargetIndex = -1;
383
384    // Target request code.
385    int mTargetRequestCode;
386
387    // True if the fragment is in the list of added fragments.
388    boolean mAdded;
389
390    // If set this fragment is being removed from its activity.
391    boolean mRemoving;
392
393    // True if the fragment is in the resumed state.
394    boolean mResumed;
395
396    // Set to true if this fragment was instantiated from a layout file.
397    boolean mFromLayout;
398
399    // Set to true when the view has actually been inflated in its layout.
400    boolean mInLayout;
401
402    // True if this fragment has been restored from previously saved state.
403    boolean mRestored;
404
405    // Number of active back stack entries this fragment is in.
406    int mBackStackNesting;
407
408    // The fragment manager we are associated with.  Set as soon as the
409    // fragment is used in a transaction; cleared after it has been removed
410    // from all transactions.
411    FragmentManagerImpl mFragmentManager;
412
413    // Activity this fragment is attached to.
414    Activity mActivity;
415
416    // The optional identifier for this fragment -- either the container ID if it
417    // was dynamically added to the view hierarchy, or the ID supplied in
418    // layout.
419    int mFragmentId;
420
421    // When a fragment is being dynamically added to the view hierarchy, this
422    // is the identifier of the parent container it is being added to.
423    int mContainerId;
424
425    // The optional named tag for this fragment -- usually used to find
426    // fragments that are not part of the layout.
427    String mTag;
428
429    // Set to true when the app has requested that this fragment be hidden
430    // from the user.
431    boolean mHidden;
432
433    // Set to true when the app has requested that this fragment be detached.
434    boolean mDetached;
435
436    // If set this fragment would like its instance retained across
437    // configuration changes.
438    boolean mRetainInstance;
439
440    // If set this fragment is being retained across the current config change.
441    boolean mRetaining;
442
443    // If set this fragment has menu items to contribute.
444    boolean mHasMenu;
445
446    // Set to true to allow the fragment's menu to be shown.
447    boolean mMenuVisible = true;
448
449    // Used to verify that subclasses call through to super class.
450    boolean mCalled;
451
452    // If app has requested a specific animation, this is the one to use.
453    int mNextAnim;
454
455    // The parent container of the fragment after dynamically added to UI.
456    ViewGroup mContainer;
457
458    // The View generated for this fragment.
459    View mView;
460
461    // Whether this fragment should defer starting until after other fragments
462    // have been started and their loaders are finished.
463    boolean mDeferStart;
464
465    // Hint provided by the app that this fragment is currently visible to the user.
466    boolean mUserVisibleHint = true;
467
468    LoaderManagerImpl mLoaderManager;
469    boolean mLoadersStarted;
470    boolean mCheckedForLoaderManager;
471
472    /**
473     * State information that has been retrieved from a fragment instance
474     * through {@link FragmentManager#saveFragmentInstanceState(Fragment)
475     * FragmentManager.saveFragmentInstanceState}.
476     */
477    public static class SavedState implements Parcelable {
478        final Bundle mState;
479
480        SavedState(Bundle state) {
481            mState = state;
482        }
483
484        SavedState(Parcel in, ClassLoader loader) {
485            mState = in.readBundle();
486            if (loader != null && mState != null) {
487                mState.setClassLoader(loader);
488            }
489        }
490
491        @Override
492        public int describeContents() {
493            return 0;
494        }
495
496        @Override
497        public void writeToParcel(Parcel dest, int flags) {
498            dest.writeBundle(mState);
499        }
500
501        public static final Parcelable.ClassLoaderCreator<SavedState> CREATOR
502                = new Parcelable.ClassLoaderCreator<SavedState>() {
503            public SavedState createFromParcel(Parcel in) {
504                return new SavedState(in, null);
505            }
506
507            public SavedState createFromParcel(Parcel in, ClassLoader loader) {
508                return new SavedState(in, loader);
509            }
510
511            public SavedState[] newArray(int size) {
512                return new SavedState[size];
513            }
514        };
515    }
516
517    /**
518     * Thrown by {@link Fragment#instantiate(Context, String, Bundle)} when
519     * there is an instantiation failure.
520     */
521    static public class InstantiationException extends AndroidRuntimeException {
522        public InstantiationException(String msg, Exception cause) {
523            super(msg, cause);
524        }
525    }
526
527    /**
528     * Default constructor.  <strong>Every</strong> fragment must have an
529     * empty constructor, so it can be instantiated when restoring its
530     * activity's state.  It is strongly recommended that subclasses do not
531     * have other constructors with parameters, since these constructors
532     * will not be called when the fragment is re-instantiated; instead,
533     * arguments can be supplied by the caller with {@link #setArguments}
534     * and later retrieved by the Fragment with {@link #getArguments}.
535     *
536     * <p>Applications should generally not implement a constructor.  The
537     * first place application code an run where the fragment is ready to
538     * be used is in {@link #onAttach(Activity)}, the point where the fragment
539     * is actually associated with its activity.  Some applications may also
540     * want to implement {@link #onInflate} to retrieve attributes from a
541     * layout resource, though should take care here because this happens for
542     * the fragment is attached to its activity.
543     */
544    public Fragment() {
545    }
546
547    /**
548     * Like {@link #instantiate(Context, String, Bundle)} but with a null
549     * argument Bundle.
550     */
551    public static Fragment instantiate(Context context, String fname) {
552        return instantiate(context, fname, null);
553    }
554
555    /**
556     * Create a new instance of a Fragment with the given class name.  This is
557     * the same as calling its empty constructor.
558     *
559     * @param context The calling context being used to instantiate the fragment.
560     * This is currently just used to get its ClassLoader.
561     * @param fname The class name of the fragment to instantiate.
562     * @param args Bundle of arguments to supply to the fragment, which it
563     * can retrieve with {@link #getArguments()}.  May be null.
564     * @return Returns a new fragment instance.
565     * @throws InstantiationException If there is a failure in instantiating
566     * the given fragment class.  This is a runtime exception; it is not
567     * normally expected to happen.
568     */
569    public static Fragment instantiate(Context context, String fname, Bundle args) {
570        try {
571            Class<?> clazz = sClassMap.get(fname);
572            if (clazz == null) {
573                // Class not found in the cache, see if it's real, and try to add it
574                clazz = context.getClassLoader().loadClass(fname);
575                sClassMap.put(fname, clazz);
576            }
577            Fragment f = (Fragment)clazz.newInstance();
578            if (args != null) {
579                args.setClassLoader(f.getClass().getClassLoader());
580                f.mArguments = args;
581            }
582            return f;
583        } catch (ClassNotFoundException e) {
584            throw new InstantiationException("Unable to instantiate fragment " + fname
585                    + ": make sure class name exists, is public, and has an"
586                    + " empty constructor that is public", e);
587        } catch (java.lang.InstantiationException e) {
588            throw new InstantiationException("Unable to instantiate fragment " + fname
589                    + ": make sure class name exists, is public, and has an"
590                    + " empty constructor that is public", e);
591        } catch (IllegalAccessException 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        }
596    }
597
598    final void restoreViewState() {
599        if (mSavedViewState != null) {
600            mView.restoreHierarchyState(mSavedViewState);
601            mSavedViewState = null;
602        }
603    }
604
605    final void setIndex(int index) {
606        mIndex = index;
607        mWho = "android:fragment:" + mIndex;
608   }
609
610    final boolean isInBackStack() {
611        return mBackStackNesting > 0;
612    }
613
614    /**
615     * Subclasses can not override equals().
616     */
617    @Override final public boolean equals(Object o) {
618        return super.equals(o);
619    }
620
621    /**
622     * Subclasses can not override hashCode().
623     */
624    @Override final public int hashCode() {
625        return super.hashCode();
626    }
627
628    @Override
629    public String toString() {
630        StringBuilder sb = new StringBuilder(128);
631        DebugUtils.buildShortClassTag(this, sb);
632        if (mIndex >= 0) {
633            sb.append(" #");
634            sb.append(mIndex);
635        }
636        if (mFragmentId != 0) {
637            sb.append(" id=0x");
638            sb.append(Integer.toHexString(mFragmentId));
639        }
640        if (mTag != null) {
641            sb.append(" ");
642            sb.append(mTag);
643        }
644        sb.append('}');
645        return sb.toString();
646    }
647
648    /**
649     * Return the identifier this fragment is known by.  This is either
650     * the android:id value supplied in a layout or the container view ID
651     * supplied when adding the fragment.
652     */
653    final public int getId() {
654        return mFragmentId;
655    }
656
657    /**
658     * Get the tag name of the fragment, if specified.
659     */
660    final public String getTag() {
661        return mTag;
662    }
663
664    /**
665     * Supply the construction arguments for this fragment.  This can only
666     * be called before the fragment has been attached to its activity; that
667     * is, you should call it immediately after constructing the fragment.  The
668     * arguments supplied here will be retained across fragment destroy and
669     * creation.
670     */
671    public void setArguments(Bundle args) {
672        if (mIndex >= 0) {
673            throw new IllegalStateException("Fragment already active");
674        }
675        mArguments = args;
676    }
677
678    /**
679     * Return the arguments supplied when the fragment was instantiated,
680     * if any.
681     */
682    final public Bundle getArguments() {
683        return mArguments;
684    }
685
686    /**
687     * Set the initial saved state that this Fragment should restore itself
688     * from when first being constructed, as returned by
689     * {@link FragmentManager#saveFragmentInstanceState(Fragment)
690     * FragmentManager.saveFragmentInstanceState}.
691     *
692     * @param state The state the fragment should be restored from.
693     */
694    public void setInitialSavedState(SavedState state) {
695        if (mIndex >= 0) {
696            throw new IllegalStateException("Fragment already active");
697        }
698        mSavedFragmentState = state != null && state.mState != null
699                ? state.mState : null;
700    }
701
702    /**
703     * Optional target for this fragment.  This may be used, for example,
704     * if this fragment is being started by another, and when done wants to
705     * give a result back to the first.  The target set here is retained
706     * across instances via {@link FragmentManager#putFragment
707     * FragmentManager.putFragment()}.
708     *
709     * @param fragment The fragment that is the target of this one.
710     * @param requestCode Optional request code, for convenience if you
711     * are going to call back with {@link #onActivityResult(int, int, Intent)}.
712     */
713    public void setTargetFragment(Fragment fragment, int requestCode) {
714        mTarget = fragment;
715        mTargetRequestCode = requestCode;
716    }
717
718    /**
719     * Return the target fragment set by {@link #setTargetFragment}.
720     */
721    final public Fragment getTargetFragment() {
722        return mTarget;
723    }
724
725    /**
726     * Return the target request code set by {@link #setTargetFragment}.
727     */
728    final public int getTargetRequestCode() {
729        return mTargetRequestCode;
730    }
731
732    /**
733     * Return the Activity this fragment is currently associated with.
734     */
735    final public Activity getActivity() {
736        return mActivity;
737    }
738
739    /**
740     * Return <code>getActivity().getResources()</code>.
741     */
742    final public Resources getResources() {
743        if (mActivity == null) {
744            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
745        }
746        return mActivity.getResources();
747    }
748
749    /**
750     * Return a localized, styled CharSequence from the application's package's
751     * default string table.
752     *
753     * @param resId Resource id for the CharSequence text
754     */
755    public final CharSequence getText(int resId) {
756        return getResources().getText(resId);
757    }
758
759    /**
760     * Return a localized string from the application's package's
761     * default string table.
762     *
763     * @param resId Resource id for the string
764     */
765    public final String getString(int resId) {
766        return getResources().getString(resId);
767    }
768
769    /**
770     * Return a localized formatted string from the application's package's
771     * default string table, substituting the format arguments as defined in
772     * {@link java.util.Formatter} and {@link java.lang.String#format}.
773     *
774     * @param resId Resource id for the format string
775     * @param formatArgs The format arguments that will be used for substitution.
776     */
777
778    public final String getString(int resId, Object... formatArgs) {
779        return getResources().getString(resId, formatArgs);
780    }
781
782    /**
783     * Return the FragmentManager for interacting with fragments associated
784     * with this fragment's activity.  Note that this will be non-null slightly
785     * before {@link #getActivity()}, during the time from when the fragment is
786     * placed in a {@link FragmentTransaction} until it is committed and
787     * attached to its activity.
788     */
789    final public FragmentManager getFragmentManager() {
790        return mFragmentManager;
791    }
792
793    /**
794     * Return true if the fragment is currently added to its activity.
795     */
796    final public boolean isAdded() {
797        return mActivity != null && mAdded;
798    }
799
800    /**
801     * Return true if the fragment has been explicitly detached from the UI.
802     * That is, {@link FragmentTransaction#detach(Fragment)
803     * FragmentTransaction.detach(Fragment)} has been used on it.
804     */
805    final public boolean isDetached() {
806        return mDetached;
807    }
808
809    /**
810     * Return true if this fragment is currently being removed from its
811     * activity.  This is  <em>not</em> whether its activity is finishing, but
812     * rather whether it is in the process of being removed from its activity.
813     */
814    final public boolean isRemoving() {
815        return mRemoving;
816    }
817
818    /**
819     * Return true if the layout is included as part of an activity view
820     * hierarchy via the &lt;fragment&gt; tag.  This will always be true when
821     * fragments are created through the &lt;fragment&gt; tag, <em>except</em>
822     * in the case where an old fragment is restored from a previous state and
823     * it does not appear in the layout of the current state.
824     */
825    final public boolean isInLayout() {
826        return mInLayout;
827    }
828
829    /**
830     * Return true if the fragment is in the resumed state.  This is true
831     * for the duration of {@link #onResume()} and {@link #onPause()} as well.
832     */
833    final public boolean isResumed() {
834        return mResumed;
835    }
836
837    /**
838     * Return true if the fragment is currently visible to the user.  This means
839     * it: (1) has been added, (2) has its view attached to the window, and
840     * (3) is not hidden.
841     */
842    final public boolean isVisible() {
843        return isAdded() && !isHidden() && mView != null
844                && mView.getWindowToken() != null && mView.getVisibility() == View.VISIBLE;
845    }
846
847    /**
848     * Return true if the fragment has been hidden.  By default fragments
849     * are shown.  You can find out about changes to this state with
850     * {@link #onHiddenChanged}.  Note that the hidden state is orthogonal
851     * to other states -- that is, to be visible to the user, a fragment
852     * must be both started and not hidden.
853     */
854    final public boolean isHidden() {
855        return mHidden;
856    }
857
858    /**
859     * Called when the hidden state (as returned by {@link #isHidden()} of
860     * the fragment has changed.  Fragments start out not hidden; this will
861     * be called whenever the fragment changes state from that.
862     * @param hidden True if the fragment is now hidden, false if it is not
863     * visible.
864     */
865    public void onHiddenChanged(boolean hidden) {
866    }
867
868    /**
869     * Control whether a fragment instance is retained across Activity
870     * re-creation (such as from a configuration change).  This can only
871     * be used with fragments not in the back stack.  If set, the fragment
872     * lifecycle will be slightly different when an activity is recreated:
873     * <ul>
874     * <li> {@link #onDestroy()} will not be called (but {@link #onDetach()} still
875     * will be, because the fragment is being detached from its current activity).
876     * <li> {@link #onCreate(Bundle)} will not be called since the fragment
877     * is not being re-created.
878     * <li> {@link #onAttach(Activity)} and {@link #onActivityCreated(Bundle)} <b>will</b>
879     * still be called.
880     * </ul>
881     */
882    public void setRetainInstance(boolean retain) {
883        mRetainInstance = retain;
884    }
885
886    final public boolean getRetainInstance() {
887        return mRetainInstance;
888    }
889
890    /**
891     * Report that this fragment would like to participate in populating
892     * the options menu by receiving a call to {@link #onCreateOptionsMenu}
893     * and related methods.
894     *
895     * @param hasMenu If true, the fragment has menu items to contribute.
896     */
897    public void setHasOptionsMenu(boolean hasMenu) {
898        if (mHasMenu != hasMenu) {
899            mHasMenu = hasMenu;
900            if (isAdded() && !isHidden()) {
901                mFragmentManager.invalidateOptionsMenu();
902            }
903        }
904    }
905
906    /**
907     * Set a hint for whether this fragment's menu should be visible.  This
908     * is useful if you know that a fragment has been placed in your view
909     * hierarchy so that the user can not currently seen it, so any menu items
910     * it has should also not be shown.
911     *
912     * @param menuVisible The default is true, meaning the fragment's menu will
913     * be shown as usual.  If false, the user will not see the menu.
914     */
915    public void setMenuVisibility(boolean menuVisible) {
916        if (mMenuVisible != menuVisible) {
917            mMenuVisible = menuVisible;
918            if (mHasMenu && isAdded() && !isHidden()) {
919                mFragmentManager.invalidateOptionsMenu();
920            }
921        }
922    }
923
924    /**
925     * Set a hint to the system about whether this fragment's UI is currently visible
926     * to the user. This hint defaults to true and is persistent across fragment instance
927     * state save and restore.
928     *
929     * <p>An app may set this to false to indicate that the fragment's UI is
930     * scrolled out of visibility or is otherwise not directly visible to the user.
931     * This may be used by the system to prioritize operations such as fragment lifecycle updates
932     * or loader ordering behavior.</p>
933     *
934     * @param isVisibleToUser true if this fragment's UI is currently visible to the user (default),
935     *                        false if it is not.
936     */
937    public void setUserVisibleHint(boolean isVisibleToUser) {
938        if (!mUserVisibleHint && isVisibleToUser && mState < STARTED) {
939            mFragmentManager.performPendingDeferredStart(this);
940        }
941        mUserVisibleHint = isVisibleToUser;
942        mDeferStart = !isVisibleToUser;
943    }
944
945    /**
946     * @return The current value of the user-visible hint on this fragment.
947     * @see #setUserVisibleHint(boolean)
948     */
949    public boolean getUserVisibleHint() {
950        return mUserVisibleHint;
951    }
952
953    /**
954     * Return the LoaderManager for this fragment, creating it if needed.
955     */
956    public LoaderManager getLoaderManager() {
957        if (mLoaderManager != null) {
958            return mLoaderManager;
959        }
960        if (mActivity == null) {
961            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
962        }
963        mCheckedForLoaderManager = true;
964        mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, true);
965        return mLoaderManager;
966    }
967
968    /**
969     * Call {@link Activity#startActivity(Intent)} on the fragment's
970     * containing Activity.
971     *
972     * @param intent The intent to start.
973     */
974    public void startActivity(Intent intent) {
975        startActivity(intent, null);
976    }
977
978    /**
979     * Call {@link Activity#startActivity(Intent, Bundle)} on the fragment's
980     * containing Activity.
981     *
982     * @param intent The intent to start.
983     * @param options Additional options for how the Activity should be started.
984     * See {@link android.content.Context#startActivity(Intent, Bundle)
985     * Context.startActivity(Intent, Bundle)} for more details.
986     */
987    public void startActivity(Intent intent, Bundle options) {
988        if (mActivity == null) {
989            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
990        }
991        if (options != null) {
992            mActivity.startActivityFromFragment(this, intent, -1, options);
993        } else {
994            // Note we want to go through this call for compatibility with
995            // applications that may have overridden the method.
996            mActivity.startActivityFromFragment(this, intent, -1);
997        }
998    }
999
1000    /**
1001     * Call {@link Activity#startActivityForResult(Intent, int)} on the fragment's
1002     * containing Activity.
1003     */
1004    public void startActivityForResult(Intent intent, int requestCode) {
1005        startActivityForResult(intent, requestCode, null);
1006    }
1007
1008    /**
1009     * Call {@link Activity#startActivityForResult(Intent, int, Bundle)} on the fragment's
1010     * containing Activity.
1011     */
1012    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
1013        if (mActivity == null) {
1014            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1015        }
1016        if (options != null) {
1017            mActivity.startActivityFromFragment(this, intent, requestCode, options);
1018        } else {
1019            // Note we want to go through this call for compatibility with
1020            // applications that may have overridden the method.
1021            mActivity.startActivityFromFragment(this, intent, requestCode, options);
1022        }
1023    }
1024
1025    /**
1026     * Receive the result from a previous call to
1027     * {@link #startActivityForResult(Intent, int)}.  This follows the
1028     * related Activity API as described there in
1029     * {@link Activity#onActivityResult(int, int, Intent)}.
1030     *
1031     * @param requestCode The integer request code originally supplied to
1032     *                    startActivityForResult(), allowing you to identify who this
1033     *                    result came from.
1034     * @param resultCode The integer result code returned by the child activity
1035     *                   through its setResult().
1036     * @param data An Intent, which can return result data to the caller
1037     *               (various data can be attached to Intent "extras").
1038     */
1039    public void onActivityResult(int requestCode, int resultCode, Intent data) {
1040    }
1041
1042    /**
1043     * @hide Hack so that DialogFragment can make its Dialog before creating
1044     * its views, and the view construction can use the dialog's context for
1045     * inflation.  Maybe this should become a public API. Note sure.
1046     */
1047    public LayoutInflater getLayoutInflater(Bundle savedInstanceState) {
1048        return mActivity.getLayoutInflater();
1049    }
1050
1051    /**
1052     * @deprecated Use {@link #onInflate(Activity, AttributeSet, Bundle)} instead.
1053     */
1054    @Deprecated
1055    public void onInflate(AttributeSet attrs, Bundle savedInstanceState) {
1056        mCalled = true;
1057    }
1058
1059    /**
1060     * Called when a fragment is being created as part of a view layout
1061     * inflation, typically from setting the content view of an activity.  This
1062     * may be called immediately after the fragment is created from a <fragment>
1063     * tag in a layout file.  Note this is <em>before</em> the fragment's
1064     * {@link #onAttach(Activity)} has been called; all you should do here is
1065     * parse the attributes and save them away.
1066     *
1067     * <p>This is called every time the fragment is inflated, even if it is
1068     * being inflated into a new instance with saved state.  It typically makes
1069     * sense to re-parse the parameters each time, to allow them to change with
1070     * different configurations.</p>
1071     *
1072     * <p>Here is a typical implementation of a fragment that can take parameters
1073     * both through attributes supplied here as well from {@link #getArguments()}:</p>
1074     *
1075     * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
1076     *      fragment}
1077     *
1078     * <p>Note that parsing the XML attributes uses a "styleable" resource.  The
1079     * declaration for the styleable used here is:</p>
1080     *
1081     * {@sample development/samples/ApiDemos/res/values/attrs.xml fragment_arguments}
1082     *
1083     * <p>The fragment can then be declared within its activity's content layout
1084     * through a tag like this:</p>
1085     *
1086     * {@sample development/samples/ApiDemos/res/layout/fragment_arguments.xml from_attributes}
1087     *
1088     * <p>This fragment can also be created dynamically from arguments given
1089     * at runtime in the arguments Bundle; here is an example of doing so at
1090     * creation of the containing activity:</p>
1091     *
1092     * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
1093     *      create}
1094     *
1095     * @param activity The Activity that is inflating this fragment.
1096     * @param attrs The attributes at the tag where the fragment is
1097     * being created.
1098     * @param savedInstanceState If the fragment is being re-created from
1099     * a previous saved state, this is the state.
1100     */
1101    public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
1102        onInflate(attrs, savedInstanceState);
1103        mCalled = true;
1104    }
1105
1106    /**
1107     * Called when a fragment is first attached to its activity.
1108     * {@link #onCreate(Bundle)} will be called after this.
1109     */
1110    public void onAttach(Activity activity) {
1111        mCalled = true;
1112    }
1113
1114    /**
1115     * Called when a fragment loads an animation.
1116     */
1117    public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) {
1118        return null;
1119    }
1120
1121    /**
1122     * Called to do initial creation of a fragment.  This is called after
1123     * {@link #onAttach(Activity)} and before
1124     * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
1125     *
1126     * <p>Note that this can be called while the fragment's activity is
1127     * still in the process of being created.  As such, you can not rely
1128     * on things like the activity's content view hierarchy being initialized
1129     * at this point.  If you want to do work once the activity itself is
1130     * created, see {@link #onActivityCreated(Bundle)}.
1131     *
1132     * @param savedInstanceState If the fragment is being re-created from
1133     * a previous saved state, this is the state.
1134     */
1135    public void onCreate(Bundle savedInstanceState) {
1136        mCalled = true;
1137    }
1138
1139    /**
1140     * Called immediately after {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}
1141     * has returned, but before any saved state has been restored in to the view.
1142     * This gives subclasses a chance to initialize themselves once
1143     * they know their view hierarchy has been completely created.  The fragment's
1144     * view hierarchy is not however attached to its parent at this point.
1145     * @param view The View returned by {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
1146     * @param savedInstanceState If non-null, this fragment is being re-constructed
1147     * from a previous saved state as given here.
1148     */
1149    public void onViewCreated(View view, Bundle savedInstanceState) {
1150    }
1151
1152    /**
1153     * Called to have the fragment instantiate its user interface view.
1154     * This is optional, and non-graphical fragments can return null (which
1155     * is the default implementation).  This will be called between
1156     * {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}.
1157     *
1158     * <p>If you return a View from here, you will later be called in
1159     * {@link #onDestroyView} when the view is being released.
1160     *
1161     * @param inflater The LayoutInflater object that can be used to inflate
1162     * any views in the fragment,
1163     * @param container If non-null, this is the parent view that the fragment's
1164     * UI should be attached to.  The fragment should not add the view itself,
1165     * but this can be used to generate the LayoutParams of the view.
1166     * @param savedInstanceState If non-null, this fragment is being re-constructed
1167     * from a previous saved state as given here.
1168     *
1169     * @return Return the View for the fragment's UI, or null.
1170     */
1171    public View onCreateView(LayoutInflater inflater, ViewGroup container,
1172            Bundle savedInstanceState) {
1173        return null;
1174    }
1175
1176    /**
1177     * Get the root view for the fragment's layout (the one returned by {@link #onCreateView}),
1178     * if provided.
1179     *
1180     * @return The fragment's root view, or null if it has no layout.
1181     */
1182    public View getView() {
1183        return mView;
1184    }
1185
1186    /**
1187     * Called when the fragment's activity has been created and this
1188     * fragment's view hierarchy instantiated.  It can be used to do final
1189     * initialization once these pieces are in place, such as retrieving
1190     * views or restoring state.  It is also useful for fragments that use
1191     * {@link #setRetainInstance(boolean)} to retain their instance,
1192     * as this callback tells the fragment when it is fully associated with
1193     * the new activity instance.  This is called after {@link #onCreateView}
1194     * and before {@link #onStart()}.
1195     *
1196     * @param savedInstanceState If the fragment is being re-created from
1197     * a previous saved state, this is the state.
1198     */
1199    public void onActivityCreated(Bundle savedInstanceState) {
1200        mCalled = true;
1201    }
1202
1203    /**
1204     * Called when the Fragment is visible to the user.  This is generally
1205     * tied to {@link Activity#onStart() Activity.onStart} of the containing
1206     * Activity's lifecycle.
1207     */
1208    public void onStart() {
1209        mCalled = true;
1210
1211        if (!mLoadersStarted) {
1212            mLoadersStarted = true;
1213            if (!mCheckedForLoaderManager) {
1214                mCheckedForLoaderManager = true;
1215                mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
1216            }
1217            if (mLoaderManager != null) {
1218                mLoaderManager.doStart();
1219            }
1220        }
1221    }
1222
1223    /**
1224     * Called when the fragment is visible to the user and actively running.
1225     * This is generally
1226     * tied to {@link Activity#onResume() Activity.onResume} of the containing
1227     * Activity's lifecycle.
1228     */
1229    public void onResume() {
1230        mCalled = true;
1231    }
1232
1233    /**
1234     * Called to ask the fragment to save its current dynamic state, so it
1235     * can later be reconstructed in a new instance of its process is
1236     * restarted.  If a new instance of the fragment later needs to be
1237     * created, the data you place in the Bundle here will be available
1238     * in the Bundle given to {@link #onCreate(Bundle)},
1239     * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}, and
1240     * {@link #onActivityCreated(Bundle)}.
1241     *
1242     * <p>This corresponds to {@link Activity#onSaveInstanceState(Bundle)
1243     * Activity.onSaveInstanceState(Bundle)} and most of the discussion there
1244     * applies here as well.  Note however: <em>this method may be called
1245     * at any time before {@link #onDestroy()}</em>.  There are many situations
1246     * where a fragment may be mostly torn down (such as when placed on the
1247     * back stack with no UI showing), but its state will not be saved until
1248     * its owning activity actually needs to save its state.
1249     *
1250     * @param outState Bundle in which to place your saved state.
1251     */
1252    public void onSaveInstanceState(Bundle outState) {
1253    }
1254
1255    public void onConfigurationChanged(Configuration newConfig) {
1256        mCalled = true;
1257    }
1258
1259    /**
1260     * Called when the Fragment is no longer resumed.  This is generally
1261     * tied to {@link Activity#onPause() Activity.onPause} of the containing
1262     * Activity's lifecycle.
1263     */
1264    public void onPause() {
1265        mCalled = true;
1266    }
1267
1268    /**
1269     * Called when the Fragment is no longer started.  This is generally
1270     * tied to {@link Activity#onStop() Activity.onStop} of the containing
1271     * Activity's lifecycle.
1272     */
1273    public void onStop() {
1274        mCalled = true;
1275    }
1276
1277    public void onLowMemory() {
1278        mCalled = true;
1279    }
1280
1281    public void onTrimMemory(int level) {
1282        mCalled = true;
1283    }
1284
1285    /**
1286     * Called when the view previously created by {@link #onCreateView} has
1287     * been detached from the fragment.  The next time the fragment needs
1288     * to be displayed, a new view will be created.  This is called
1289     * after {@link #onStop()} and before {@link #onDestroy()}.  It is called
1290     * <em>regardless</em> of whether {@link #onCreateView} returned a
1291     * non-null view.  Internally it is called after the view's state has
1292     * been saved but before it has been removed from its parent.
1293     */
1294    public void onDestroyView() {
1295        mCalled = true;
1296    }
1297
1298    /**
1299     * Called when the fragment is no longer in use.  This is called
1300     * after {@link #onStop()} and before {@link #onDetach()}.
1301     */
1302    public void onDestroy() {
1303        mCalled = true;
1304        //Log.v("foo", "onDestroy: mCheckedForLoaderManager=" + mCheckedForLoaderManager
1305        //        + " mLoaderManager=" + mLoaderManager);
1306        if (!mCheckedForLoaderManager) {
1307            mCheckedForLoaderManager = true;
1308            mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
1309        }
1310        if (mLoaderManager != null) {
1311            mLoaderManager.doDestroy();
1312        }
1313    }
1314
1315    /**
1316     * Called by the fragment manager once this fragment has been removed,
1317     * so that we don't have any left-over state if the application decides
1318     * to re-use the instance.  This only clears state that the framework
1319     * internally manages, not things the application sets.
1320     */
1321    void initState() {
1322        mIndex = -1;
1323        mWho = null;
1324        mAdded = false;
1325        mRemoving = false;
1326        mResumed = false;
1327        mFromLayout = false;
1328        mInLayout = false;
1329        mRestored = false;
1330        mBackStackNesting = 0;
1331        mFragmentManager = null;
1332        mActivity = null;
1333        mFragmentId = 0;
1334        mContainerId = 0;
1335        mTag = null;
1336        mHidden = false;
1337        mDetached = false;
1338        mRetaining = false;
1339        mLoaderManager = null;
1340        mLoadersStarted = false;
1341        mCheckedForLoaderManager = false;
1342    }
1343
1344    /**
1345     * Called when the fragment is no longer attached to its activity.  This
1346     * is called after {@link #onDestroy()}.
1347     */
1348    public void onDetach() {
1349        mCalled = true;
1350    }
1351
1352    /**
1353     * Initialize the contents of the Activity's standard options menu.  You
1354     * should place your menu items in to <var>menu</var>.  For this method
1355     * to be called, you must have first called {@link #setHasOptionsMenu}.  See
1356     * {@link Activity#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu}
1357     * for more information.
1358     *
1359     * @param menu The options menu in which you place your items.
1360     *
1361     * @see #setHasOptionsMenu
1362     * @see #onPrepareOptionsMenu
1363     * @see #onOptionsItemSelected
1364     */
1365    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
1366    }
1367
1368    /**
1369     * Prepare the Screen's standard options menu to be displayed.  This is
1370     * called right before the menu is shown, every time it is shown.  You can
1371     * use this method to efficiently enable/disable items or otherwise
1372     * dynamically modify the contents.  See
1373     * {@link Activity#onPrepareOptionsMenu(Menu) Activity.onPrepareOptionsMenu}
1374     * for more information.
1375     *
1376     * @param menu The options menu as last shown or first initialized by
1377     *             onCreateOptionsMenu().
1378     *
1379     * @see #setHasOptionsMenu
1380     * @see #onCreateOptionsMenu
1381     */
1382    public void onPrepareOptionsMenu(Menu menu) {
1383    }
1384
1385    /**
1386     * Called when this fragment's option menu items are no longer being
1387     * included in the overall options menu.  Receiving this call means that
1388     * the menu needed to be rebuilt, but this fragment's items were not
1389     * included in the newly built menu (its {@link #onCreateOptionsMenu(Menu, MenuInflater)}
1390     * was not called).
1391     */
1392    public void onDestroyOptionsMenu() {
1393    }
1394
1395    /**
1396     * This hook is called whenever an item in your options menu is selected.
1397     * The default implementation simply returns false to have the normal
1398     * processing happen (calling the item's Runnable or sending a message to
1399     * its Handler as appropriate).  You can use this method for any items
1400     * for which you would like to do processing without those other
1401     * facilities.
1402     *
1403     * <p>Derived classes should call through to the base class for it to
1404     * perform the default menu handling.
1405     *
1406     * @param item The menu item that was selected.
1407     *
1408     * @return boolean Return false to allow normal menu processing to
1409     *         proceed, true to consume it here.
1410     *
1411     * @see #onCreateOptionsMenu
1412     */
1413    public boolean onOptionsItemSelected(MenuItem item) {
1414        return false;
1415    }
1416
1417    /**
1418     * This hook is called whenever the options menu is being closed (either by the user canceling
1419     * the menu with the back/menu button, or when an item is selected).
1420     *
1421     * @param menu The options menu as last shown or first initialized by
1422     *             onCreateOptionsMenu().
1423     */
1424    public void onOptionsMenuClosed(Menu menu) {
1425    }
1426
1427    /**
1428     * Called when a context menu for the {@code view} is about to be shown.
1429     * Unlike {@link #onCreateOptionsMenu}, this will be called every
1430     * time the context menu is about to be shown and should be populated for
1431     * the view (or item inside the view for {@link AdapterView} subclasses,
1432     * this can be found in the {@code menuInfo})).
1433     * <p>
1434     * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
1435     * item has been selected.
1436     * <p>
1437     * The default implementation calls up to
1438     * {@link Activity#onCreateContextMenu Activity.onCreateContextMenu}, though
1439     * you can not call this implementation if you don't want that behavior.
1440     * <p>
1441     * It is not safe to hold onto the context menu after this method returns.
1442     * {@inheritDoc}
1443     */
1444    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1445        getActivity().onCreateContextMenu(menu, v, menuInfo);
1446    }
1447
1448    /**
1449     * Registers a context menu to be shown for the given view (multiple views
1450     * can show the context menu). This method will set the
1451     * {@link OnCreateContextMenuListener} on the view to this fragment, so
1452     * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
1453     * called when it is time to show the context menu.
1454     *
1455     * @see #unregisterForContextMenu(View)
1456     * @param view The view that should show a context menu.
1457     */
1458    public void registerForContextMenu(View view) {
1459        view.setOnCreateContextMenuListener(this);
1460    }
1461
1462    /**
1463     * Prevents a context menu to be shown for the given view. This method will
1464     * remove the {@link OnCreateContextMenuListener} on the view.
1465     *
1466     * @see #registerForContextMenu(View)
1467     * @param view The view that should stop showing a context menu.
1468     */
1469    public void unregisterForContextMenu(View view) {
1470        view.setOnCreateContextMenuListener(null);
1471    }
1472
1473    /**
1474     * This hook is called whenever an item in a context menu is selected. The
1475     * default implementation simply returns false to have the normal processing
1476     * happen (calling the item's Runnable or sending a message to its Handler
1477     * as appropriate). You can use this method for any items for which you
1478     * would like to do processing without those other facilities.
1479     * <p>
1480     * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
1481     * View that added this menu item.
1482     * <p>
1483     * Derived classes should call through to the base class for it to perform
1484     * the default menu handling.
1485     *
1486     * @param item The context menu item that was selected.
1487     * @return boolean Return false to allow normal context menu processing to
1488     *         proceed, true to consume it here.
1489     */
1490    public boolean onContextItemSelected(MenuItem item) {
1491        return false;
1492    }
1493
1494    /**
1495     * Print the Fragments's state into the given stream.
1496     *
1497     * @param prefix Text to print at the front of each line.
1498     * @param fd The raw file descriptor that the dump is being sent to.
1499     * @param writer The PrintWriter to which you should dump your state.  This will be
1500     * closed for you after you return.
1501     * @param args additional arguments to the dump request.
1502     */
1503    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
1504        writer.print(prefix); writer.print("mFragmentId=#");
1505                writer.print(Integer.toHexString(mFragmentId));
1506                writer.print(" mContainerId#=");
1507                writer.print(Integer.toHexString(mContainerId));
1508                writer.print(" mTag="); writer.println(mTag);
1509        writer.print(prefix); writer.print("mState="); writer.print(mState);
1510                writer.print(" mIndex="); writer.print(mIndex);
1511                writer.print(" mWho="); writer.print(mWho);
1512                writer.print(" mBackStackNesting="); writer.println(mBackStackNesting);
1513        writer.print(prefix); writer.print("mAdded="); writer.print(mAdded);
1514                writer.print(" mRemoving="); writer.print(mRemoving);
1515                writer.print(" mResumed="); writer.print(mResumed);
1516                writer.print(" mFromLayout="); writer.print(mFromLayout);
1517                writer.print(" mInLayout="); writer.println(mInLayout);
1518        writer.print(prefix); writer.print("mHidden="); writer.print(mHidden);
1519                writer.print(" mDetached="); writer.print(mDetached);
1520                writer.print(" mMenuVisible="); writer.print(mMenuVisible);
1521                writer.print(" mHasMenu="); writer.println(mHasMenu);
1522        writer.print(prefix); writer.print("mRetainInstance="); writer.print(mRetainInstance);
1523                writer.print(" mRetaining="); writer.print(mRetaining);
1524                writer.print(" mUserVisibleHint="); writer.println(mUserVisibleHint);
1525        if (mFragmentManager != null) {
1526            writer.print(prefix); writer.print("mFragmentManager=");
1527                    writer.println(mFragmentManager);
1528        }
1529        if (mActivity != null) {
1530            writer.print(prefix); writer.print("mActivity=");
1531                    writer.println(mActivity);
1532        }
1533        if (mArguments != null) {
1534            writer.print(prefix); writer.print("mArguments="); writer.println(mArguments);
1535        }
1536        if (mSavedFragmentState != null) {
1537            writer.print(prefix); writer.print("mSavedFragmentState=");
1538                    writer.println(mSavedFragmentState);
1539        }
1540        if (mSavedViewState != null) {
1541            writer.print(prefix); writer.print("mSavedViewState=");
1542                    writer.println(mSavedViewState);
1543        }
1544        if (mTarget != null) {
1545            writer.print(prefix); writer.print("mTarget="); writer.print(mTarget);
1546                    writer.print(" mTargetRequestCode=");
1547                    writer.println(mTargetRequestCode);
1548        }
1549        if (mNextAnim != 0) {
1550            writer.print(prefix); writer.print("mNextAnim="); writer.println(mNextAnim);
1551        }
1552        if (mContainer != null) {
1553            writer.print(prefix); writer.print("mContainer="); writer.println(mContainer);
1554        }
1555        if (mView != null) {
1556            writer.print(prefix); writer.print("mView="); writer.println(mView);
1557        }
1558        if (mAnimatingAway != null) {
1559            writer.print(prefix); writer.print("mAnimatingAway="); writer.println(mAnimatingAway);
1560            writer.print(prefix); writer.print("mStateAfterAnimating=");
1561                    writer.println(mStateAfterAnimating);
1562        }
1563        if (mLoaderManager != null) {
1564            writer.print(prefix); writer.println("Loader Manager:");
1565            mLoaderManager.dump(prefix + "  ", fd, writer, args);
1566        }
1567    }
1568
1569    void performStart() {
1570        onStart();
1571        if (mLoaderManager != null) {
1572            mLoaderManager.doReportStart();
1573        }
1574    }
1575
1576    void performStop() {
1577        onStop();
1578
1579        if (mLoadersStarted) {
1580            mLoadersStarted = false;
1581            if (!mCheckedForLoaderManager) {
1582                mCheckedForLoaderManager = true;
1583                mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
1584            }
1585            if (mLoaderManager != null) {
1586                if (mActivity == null || !mActivity.mChangingConfigurations) {
1587                    mLoaderManager.doStop();
1588                } else {
1589                    mLoaderManager.doRetain();
1590                }
1591            }
1592        }
1593    }
1594
1595    void performDestroyView() {
1596        onDestroyView();
1597        if (mLoaderManager != null) {
1598            mLoaderManager.doReportNextStart();
1599        }
1600    }
1601}
1602