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