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