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