1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
19import android.animation.Animator;
20import android.content.ComponentCallbacks2;
21import android.content.Context;
22import android.content.Intent;
23import android.content.res.Configuration;
24import android.content.res.Resources;
25import android.os.Bundle;
26import android.os.Parcel;
27import android.os.Parcelable;
28import android.util.AndroidRuntimeException;
29import android.util.AttributeSet;
30import android.util.DebugUtils;
31import android.util.SparseArray;
32import android.view.ContextMenu;
33import android.view.ContextMenu.ContextMenuInfo;
34import android.view.LayoutInflater;
35import android.view.Menu;
36import android.view.MenuInflater;
37import android.view.MenuItem;
38import android.view.View;
39import android.view.View.OnCreateContextMenuListener;
40import android.view.ViewGroup;
41import android.widget.AdapterView;
42
43import java.io.FileDescriptor;
44import java.io.PrintWriter;
45import java.util.HashMap;
46
47final class FragmentState implements Parcelable {
48    final String mClassName;
49    final int mIndex;
50    final boolean mFromLayout;
51    final int mFragmentId;
52    final int mContainerId;
53    final String mTag;
54    final boolean mRetainInstance;
55    final boolean mDetached;
56    final Bundle mArguments;
57
58    Bundle mSavedFragmentState;
59
60    Fragment mInstance;
61
62    public FragmentState(Fragment frag) {
63        mClassName = frag.getClass().getName();
64        mIndex = frag.mIndex;
65        mFromLayout = frag.mFromLayout;
66        mFragmentId = frag.mFragmentId;
67        mContainerId = frag.mContainerId;
68        mTag = frag.mTag;
69        mRetainInstance = frag.mRetainInstance;
70        mDetached = frag.mDetached;
71        mArguments = frag.mArguments;
72    }
73
74    public FragmentState(Parcel in) {
75        mClassName = in.readString();
76        mIndex = in.readInt();
77        mFromLayout = in.readInt() != 0;
78        mFragmentId = in.readInt();
79        mContainerId = in.readInt();
80        mTag = in.readString();
81        mRetainInstance = in.readInt() != 0;
82        mDetached = in.readInt() != 0;
83        mArguments = in.readBundle();
84        mSavedFragmentState = in.readBundle();
85    }
86
87    public Fragment instantiate(Activity activity) {
88        if (mInstance != null) {
89            return mInstance;
90        }
91
92        if (mArguments != null) {
93            mArguments.setClassLoader(activity.getClassLoader());
94        }
95
96        mInstance = Fragment.instantiate(activity, mClassName, mArguments);
97
98        if (mSavedFragmentState != null) {
99            mSavedFragmentState.setClassLoader(activity.getClassLoader());
100            mInstance.mSavedFragmentState = mSavedFragmentState;
101        }
102        mInstance.setIndex(mIndex);
103        mInstance.mFromLayout = mFromLayout;
104        mInstance.mRestored = true;
105        mInstance.mFragmentId = mFragmentId;
106        mInstance.mContainerId = mContainerId;
107        mInstance.mTag = mTag;
108        mInstance.mRetainInstance = mRetainInstance;
109        mInstance.mDetached = mDetached;
110        mInstance.mFragmentManager = activity.mFragments;
111
112        return mInstance;
113    }
114
115    public int describeContents() {
116        return 0;
117    }
118
119    public void writeToParcel(Parcel dest, int flags) {
120        dest.writeString(mClassName);
121        dest.writeInt(mIndex);
122        dest.writeInt(mFromLayout ? 1 : 0);
123        dest.writeInt(mFragmentId);
124        dest.writeInt(mContainerId);
125        dest.writeString(mTag);
126        dest.writeInt(mRetainInstance ? 1 : 0);
127        dest.writeInt(mDetached ? 1 : 0);
128        dest.writeBundle(mArguments);
129        dest.writeBundle(mSavedFragmentState);
130    }
131
132    public static final Parcelable.Creator<FragmentState> CREATOR
133            = new Parcelable.Creator<FragmentState>() {
134        public FragmentState createFromParcel(Parcel in) {
135            return new FragmentState(in);
136        }
137
138        public FragmentState[] newArray(int size) {
139            return new FragmentState[size];
140        }
141    };
142}
143
144/**
145 * A Fragment is a piece of an application's user interface or behavior
146 * that can be placed in an {@link Activity}.  Interaction with fragments
147 * is done through {@link FragmentManager}, which can be obtained via
148 * {@link Activity#getFragmentManager() Activity.getFragmentManager()} and
149 * {@link Fragment#getFragmentManager() Fragment.getFragmentManager()}.
150 *
151 * <p>The Fragment class can be used many ways to achieve a wide variety of
152 * results.  It is core, it represents a particular operation or interface
153 * that is running within a larger {@link Activity}.  A Fragment is closely
154 * tied to the Activity it is in, and can not be used apart from one.  Though
155 * Fragment defines its own lifecycle, that lifecycle is dependent on its
156 * activity: if the activity is stopped, no fragments inside of it can be
157 * started; when the activity is destroyed, all fragments will be destroyed.
158 *
159 * <p>All subclasses of Fragment must include a public empty constructor.
160 * The framework will often re-instantiate a fragment class when needed,
161 * in particular during state restore, and needs to be able to find this
162 * constructor to instantiate it.  If the empty constructor is not available,
163 * a runtime exception will occur in some cases during state restore.
164 *
165 * <p>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    public void startActivity(Intent intent) {
970        if (mActivity == null) {
971            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
972        }
973        mActivity.startActivityFromFragment(this, intent, -1);
974    }
975
976    /**
977     * Call {@link Activity#startActivityForResult(Intent, int)} on the fragment's
978     * containing Activity.
979     */
980    public void startActivityForResult(Intent intent, int requestCode) {
981        if (mActivity == null) {
982            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
983        }
984        mActivity.startActivityFromFragment(this, intent, requestCode);
985    }
986
987    /**
988     * Receive the result from a previous call to
989     * {@link #startActivityForResult(Intent, int)}.  This follows the
990     * related Activity API as described there in
991     * {@link Activity#onActivityResult(int, int, Intent)}.
992     *
993     * @param requestCode The integer request code originally supplied to
994     *                    startActivityForResult(), allowing you to identify who this
995     *                    result came from.
996     * @param resultCode The integer result code returned by the child activity
997     *                   through its setResult().
998     * @param data An Intent, which can return result data to the caller
999     *               (various data can be attached to Intent "extras").
1000     */
1001    public void onActivityResult(int requestCode, int resultCode, Intent data) {
1002    }
1003
1004    /**
1005     * @hide Hack so that DialogFragment can make its Dialog before creating
1006     * its views, and the view construction can use the dialog's context for
1007     * inflation.  Maybe this should become a public API. Note sure.
1008     */
1009    public LayoutInflater getLayoutInflater(Bundle savedInstanceState) {
1010        return mActivity.getLayoutInflater();
1011    }
1012
1013    /**
1014     * @deprecated Use {@link #onInflate(Activity, AttributeSet, Bundle)} instead.
1015     */
1016    @Deprecated
1017    public void onInflate(AttributeSet attrs, Bundle savedInstanceState) {
1018        mCalled = true;
1019    }
1020
1021    /**
1022     * Called when a fragment is being created as part of a view layout
1023     * inflation, typically from setting the content view of an activity.  This
1024     * may be called immediately after the fragment is created from a <fragment>
1025     * tag in a layout file.  Note this is <em>before</em> the fragment's
1026     * {@link #onAttach(Activity)} has been called; all you should do here is
1027     * parse the attributes and save them away.
1028     *
1029     * <p>This is called every time the fragment is inflated, even if it is
1030     * being inflated into a new instance with saved state.  It typically makes
1031     * sense to re-parse the parameters each time, to allow them to change with
1032     * different configurations.</p>
1033     *
1034     * <p>Here is a typical implementation of a fragment that can take parameters
1035     * both through attributes supplied here as well from {@link #getArguments()}:</p>
1036     *
1037     * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
1038     *      fragment}
1039     *
1040     * <p>Note that parsing the XML attributes uses a "styleable" resource.  The
1041     * declaration for the styleable used here is:</p>
1042     *
1043     * {@sample development/samples/ApiDemos/res/values/attrs.xml fragment_arguments}
1044     *
1045     * <p>The fragment can then be declared within its activity's content layout
1046     * through a tag like this:</p>
1047     *
1048     * {@sample development/samples/ApiDemos/res/layout/fragment_arguments.xml from_attributes}
1049     *
1050     * <p>This fragment can also be created dynamically from arguments given
1051     * at runtime in the arguments Bundle; here is an example of doing so at
1052     * creation of the containing activity:</p>
1053     *
1054     * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
1055     *      create}
1056     *
1057     * @param activity The Activity that is inflating this fragment.
1058     * @param attrs The attributes at the tag where the fragment is
1059     * being created.
1060     * @param savedInstanceState If the fragment is being re-created from
1061     * a previous saved state, this is the state.
1062     */
1063    public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
1064        onInflate(attrs, savedInstanceState);
1065        mCalled = true;
1066    }
1067
1068    /**
1069     * Called when a fragment is first attached to its activity.
1070     * {@link #onCreate(Bundle)} will be called after this.
1071     */
1072    public void onAttach(Activity activity) {
1073        mCalled = true;
1074    }
1075
1076    /**
1077     * Called when a fragment loads an animation.
1078     */
1079    public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) {
1080        return null;
1081    }
1082
1083    /**
1084     * Called to do initial creation of a fragment.  This is called after
1085     * {@link #onAttach(Activity)} and before
1086     * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
1087     *
1088     * <p>Note that this can be called while the fragment's activity is
1089     * still in the process of being created.  As such, you can not rely
1090     * on things like the activity's content view hierarchy being initialized
1091     * at this point.  If you want to do work once the activity itself is
1092     * created, see {@link #onActivityCreated(Bundle)}.
1093     *
1094     * @param savedInstanceState If the fragment is being re-created from
1095     * a previous saved state, this is the state.
1096     */
1097    public void onCreate(Bundle savedInstanceState) {
1098        mCalled = true;
1099    }
1100
1101    /**
1102     * Called immediately after {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}
1103     * has returned, but before any saved state has been restored in to the view.
1104     * This gives subclasses a chance to initialize themselves once
1105     * they know their view hierarchy has been completely created.  The fragment's
1106     * view hierarchy is not however attached to its parent at this point.
1107     * @param view The View returned by {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
1108     * @param savedInstanceState If non-null, this fragment is being re-constructed
1109     * from a previous saved state as given here.
1110     */
1111    public void onViewCreated(View view, Bundle savedInstanceState) {
1112    }
1113
1114    /**
1115     * Called to have the fragment instantiate its user interface view.
1116     * This is optional, and non-graphical fragments can return null (which
1117     * is the default implementation).  This will be called between
1118     * {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}.
1119     *
1120     * <p>If you return a View from here, you will later be called in
1121     * {@link #onDestroyView} when the view is being released.
1122     *
1123     * @param inflater The LayoutInflater object that can be used to inflate
1124     * any views in the fragment,
1125     * @param container If non-null, this is the parent view that the fragment's
1126     * UI should be attached to.  The fragment should not add the view itself,
1127     * but this can be used to generate the LayoutParams of the view.
1128     * @param savedInstanceState If non-null, this fragment is being re-constructed
1129     * from a previous saved state as given here.
1130     *
1131     * @return Return the View for the fragment's UI, or null.
1132     */
1133    public View onCreateView(LayoutInflater inflater, ViewGroup container,
1134            Bundle savedInstanceState) {
1135        return null;
1136    }
1137
1138    /**
1139     * Get the root view for the fragment's layout (the one returned by {@link #onCreateView}),
1140     * if provided.
1141     *
1142     * @return The fragment's root view, or null if it has no layout.
1143     */
1144    public View getView() {
1145        return mView;
1146    }
1147
1148    /**
1149     * Called when the fragment's activity has been created and this
1150     * fragment's view hierarchy instantiated.  It can be used to do final
1151     * initialization once these pieces are in place, such as retrieving
1152     * views or restoring state.  It is also useful for fragments that use
1153     * {@link #setRetainInstance(boolean)} to retain their instance,
1154     * as this callback tells the fragment when it is fully associated with
1155     * the new activity instance.  This is called after {@link #onCreateView}
1156     * and before {@link #onStart()}.
1157     *
1158     * @param savedInstanceState If the fragment is being re-created from
1159     * a previous saved state, this is the state.
1160     */
1161    public void onActivityCreated(Bundle savedInstanceState) {
1162        mCalled = true;
1163    }
1164
1165    /**
1166     * Called when the Fragment is visible to the user.  This is generally
1167     * tied to {@link Activity#onStart() Activity.onStart} of the containing
1168     * Activity's lifecycle.
1169     */
1170    public void onStart() {
1171        mCalled = true;
1172
1173        if (!mLoadersStarted) {
1174            mLoadersStarted = true;
1175            if (!mCheckedForLoaderManager) {
1176                mCheckedForLoaderManager = true;
1177                mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
1178            }
1179            if (mLoaderManager != null) {
1180                mLoaderManager.doStart();
1181            }
1182        }
1183    }
1184
1185    /**
1186     * Called when the fragment is visible to the user and actively running.
1187     * This is generally
1188     * tied to {@link Activity#onResume() Activity.onResume} of the containing
1189     * Activity's lifecycle.
1190     */
1191    public void onResume() {
1192        mCalled = true;
1193    }
1194
1195    /**
1196     * Called to ask the fragment to save its current dynamic state, so it
1197     * can later be reconstructed in a new instance of its process is
1198     * restarted.  If a new instance of the fragment later needs to be
1199     * created, the data you place in the Bundle here will be available
1200     * in the Bundle given to {@link #onCreate(Bundle)},
1201     * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}, and
1202     * {@link #onActivityCreated(Bundle)}.
1203     *
1204     * <p>This corresponds to {@link Activity#onSaveInstanceState(Bundle)
1205     * Activity.onSaveInstanceState(Bundle)} and most of the discussion there
1206     * applies here as well.  Note however: <em>this method may be called
1207     * at any time before {@link #onDestroy()}</em>.  There are many situations
1208     * where a fragment may be mostly torn down (such as when placed on the
1209     * back stack with no UI showing), but its state will not be saved until
1210     * its owning activity actually needs to save its state.
1211     *
1212     * @param outState Bundle in which to place your saved state.
1213     */
1214    public void onSaveInstanceState(Bundle outState) {
1215    }
1216
1217    public void onConfigurationChanged(Configuration newConfig) {
1218        mCalled = true;
1219    }
1220
1221    /**
1222     * Called when the Fragment is no longer resumed.  This is generally
1223     * tied to {@link Activity#onPause() Activity.onPause} of the containing
1224     * Activity's lifecycle.
1225     */
1226    public void onPause() {
1227        mCalled = true;
1228    }
1229
1230    /**
1231     * Called when the Fragment is no longer started.  This is generally
1232     * tied to {@link Activity#onStop() Activity.onStop} of the containing
1233     * Activity's lifecycle.
1234     */
1235    public void onStop() {
1236        mCalled = true;
1237    }
1238
1239    public void onLowMemory() {
1240        mCalled = true;
1241    }
1242
1243    public void onTrimMemory(int level) {
1244        mCalled = true;
1245    }
1246
1247    /**
1248     * Called when the view previously created by {@link #onCreateView} has
1249     * been detached from the fragment.  The next time the fragment needs
1250     * to be displayed, a new view will be created.  This is called
1251     * after {@link #onStop()} and before {@link #onDestroy()}.  It is called
1252     * <em>regardless</em> of whether {@link #onCreateView} returned a
1253     * non-null view.  Internally it is called after the view's state has
1254     * been saved but before it has been removed from its parent.
1255     */
1256    public void onDestroyView() {
1257        mCalled = true;
1258    }
1259
1260    /**
1261     * Called when the fragment is no longer in use.  This is called
1262     * after {@link #onStop()} and before {@link #onDetach()}.
1263     */
1264    public void onDestroy() {
1265        mCalled = true;
1266        //Log.v("foo", "onDestroy: mCheckedForLoaderManager=" + mCheckedForLoaderManager
1267        //        + " mLoaderManager=" + mLoaderManager);
1268        if (!mCheckedForLoaderManager) {
1269            mCheckedForLoaderManager = true;
1270            mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
1271        }
1272        if (mLoaderManager != null) {
1273            mLoaderManager.doDestroy();
1274        }
1275    }
1276
1277    /**
1278     * Called by the fragment manager once this fragment has been removed,
1279     * so that we don't have any left-over state if the application decides
1280     * to re-use the instance.  This only clears state that the framework
1281     * internally manages, not things the application sets.
1282     */
1283    void initState() {
1284        mIndex = -1;
1285        mWho = null;
1286        mAdded = false;
1287        mRemoving = false;
1288        mResumed = false;
1289        mFromLayout = false;
1290        mInLayout = false;
1291        mRestored = false;
1292        mBackStackNesting = 0;
1293        mFragmentManager = null;
1294        mActivity = null;
1295        mFragmentId = 0;
1296        mContainerId = 0;
1297        mTag = null;
1298        mHidden = false;
1299        mDetached = false;
1300        mRetaining = false;
1301        mLoaderManager = null;
1302        mLoadersStarted = false;
1303        mCheckedForLoaderManager = false;
1304    }
1305
1306    /**
1307     * Called when the fragment is no longer attached to its activity.  This
1308     * is called after {@link #onDestroy()}.
1309     */
1310    public void onDetach() {
1311        mCalled = true;
1312    }
1313
1314    /**
1315     * Initialize the contents of the Activity's standard options menu.  You
1316     * should place your menu items in to <var>menu</var>.  For this method
1317     * to be called, you must have first called {@link #setHasOptionsMenu}.  See
1318     * {@link Activity#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu}
1319     * for more information.
1320     *
1321     * @param menu The options menu in which you place your items.
1322     *
1323     * @see #setHasOptionsMenu
1324     * @see #onPrepareOptionsMenu
1325     * @see #onOptionsItemSelected
1326     */
1327    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
1328    }
1329
1330    /**
1331     * Prepare the Screen's standard options menu to be displayed.  This is
1332     * called right before the menu is shown, every time it is shown.  You can
1333     * use this method to efficiently enable/disable items or otherwise
1334     * dynamically modify the contents.  See
1335     * {@link Activity#onPrepareOptionsMenu(Menu) Activity.onPrepareOptionsMenu}
1336     * for more information.
1337     *
1338     * @param menu The options menu as last shown or first initialized by
1339     *             onCreateOptionsMenu().
1340     *
1341     * @see #setHasOptionsMenu
1342     * @see #onCreateOptionsMenu
1343     */
1344    public void onPrepareOptionsMenu(Menu menu) {
1345    }
1346
1347    /**
1348     * Called when this fragment's option menu items are no longer being
1349     * included in the overall options menu.  Receiving this call means that
1350     * the menu needed to be rebuilt, but this fragment's items were not
1351     * included in the newly built menu (its {@link #onCreateOptionsMenu(Menu, MenuInflater)}
1352     * was not called).
1353     */
1354    public void onDestroyOptionsMenu() {
1355    }
1356
1357    /**
1358     * This hook is called whenever an item in your options menu is selected.
1359     * The default implementation simply returns false to have the normal
1360     * processing happen (calling the item's Runnable or sending a message to
1361     * its Handler as appropriate).  You can use this method for any items
1362     * for which you would like to do processing without those other
1363     * facilities.
1364     *
1365     * <p>Derived classes should call through to the base class for it to
1366     * perform the default menu handling.
1367     *
1368     * @param item The menu item that was selected.
1369     *
1370     * @return boolean Return false to allow normal menu processing to
1371     *         proceed, true to consume it here.
1372     *
1373     * @see #onCreateOptionsMenu
1374     */
1375    public boolean onOptionsItemSelected(MenuItem item) {
1376        return false;
1377    }
1378
1379    /**
1380     * This hook is called whenever the options menu is being closed (either by the user canceling
1381     * the menu with the back/menu button, or when an item is selected).
1382     *
1383     * @param menu The options menu as last shown or first initialized by
1384     *             onCreateOptionsMenu().
1385     */
1386    public void onOptionsMenuClosed(Menu menu) {
1387    }
1388
1389    /**
1390     * Called when a context menu for the {@code view} is about to be shown.
1391     * Unlike {@link #onCreateOptionsMenu}, this will be called every
1392     * time the context menu is about to be shown and should be populated for
1393     * the view (or item inside the view for {@link AdapterView} subclasses,
1394     * this can be found in the {@code menuInfo})).
1395     * <p>
1396     * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
1397     * item has been selected.
1398     * <p>
1399     * The default implementation calls up to
1400     * {@link Activity#onCreateContextMenu Activity.onCreateContextMenu}, though
1401     * you can not call this implementation if you don't want that behavior.
1402     * <p>
1403     * It is not safe to hold onto the context menu after this method returns.
1404     * {@inheritDoc}
1405     */
1406    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1407        getActivity().onCreateContextMenu(menu, v, menuInfo);
1408    }
1409
1410    /**
1411     * Registers a context menu to be shown for the given view (multiple views
1412     * can show the context menu). This method will set the
1413     * {@link OnCreateContextMenuListener} on the view to this fragment, so
1414     * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
1415     * called when it is time to show the context menu.
1416     *
1417     * @see #unregisterForContextMenu(View)
1418     * @param view The view that should show a context menu.
1419     */
1420    public void registerForContextMenu(View view) {
1421        view.setOnCreateContextMenuListener(this);
1422    }
1423
1424    /**
1425     * Prevents a context menu to be shown for the given view. This method will
1426     * remove the {@link OnCreateContextMenuListener} on the view.
1427     *
1428     * @see #registerForContextMenu(View)
1429     * @param view The view that should stop showing a context menu.
1430     */
1431    public void unregisterForContextMenu(View view) {
1432        view.setOnCreateContextMenuListener(null);
1433    }
1434
1435    /**
1436     * This hook is called whenever an item in a context menu is selected. The
1437     * default implementation simply returns false to have the normal processing
1438     * happen (calling the item's Runnable or sending a message to its Handler
1439     * as appropriate). You can use this method for any items for which you
1440     * would like to do processing without those other facilities.
1441     * <p>
1442     * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
1443     * View that added this menu item.
1444     * <p>
1445     * Derived classes should call through to the base class for it to perform
1446     * the default menu handling.
1447     *
1448     * @param item The context menu item that was selected.
1449     * @return boolean Return false to allow normal context menu processing to
1450     *         proceed, true to consume it here.
1451     */
1452    public boolean onContextItemSelected(MenuItem item) {
1453        return false;
1454    }
1455
1456    /**
1457     * Print the Fragments's state into the given stream.
1458     *
1459     * @param prefix Text to print at the front of each line.
1460     * @param fd The raw file descriptor that the dump is being sent to.
1461     * @param writer The PrintWriter to which you should dump your state.  This will be
1462     * closed for you after you return.
1463     * @param args additional arguments to the dump request.
1464     */
1465    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
1466        writer.print(prefix); writer.print("mFragmentId=#");
1467                writer.print(Integer.toHexString(mFragmentId));
1468                writer.print(" mContainerId#=");
1469                writer.print(Integer.toHexString(mContainerId));
1470                writer.print(" mTag="); writer.println(mTag);
1471        writer.print(prefix); writer.print("mState="); writer.print(mState);
1472                writer.print(" mIndex="); writer.print(mIndex);
1473                writer.print(" mWho="); writer.print(mWho);
1474                writer.print(" mBackStackNesting="); writer.println(mBackStackNesting);
1475        writer.print(prefix); writer.print("mAdded="); writer.print(mAdded);
1476                writer.print(" mRemoving="); writer.print(mRemoving);
1477                writer.print(" mResumed="); writer.print(mResumed);
1478                writer.print(" mFromLayout="); writer.print(mFromLayout);
1479                writer.print(" mInLayout="); writer.println(mInLayout);
1480        writer.print(prefix); writer.print("mHidden="); writer.print(mHidden);
1481                writer.print(" mDetached="); writer.print(mDetached);
1482                writer.print(" mMenuVisible="); writer.print(mMenuVisible);
1483                writer.print(" mHasMenu="); writer.println(mHasMenu);
1484        writer.print(prefix); writer.print("mRetainInstance="); writer.print(mRetainInstance);
1485                writer.print(" mRetaining="); writer.print(mRetaining);
1486                writer.print(" mUserVisibleHint="); writer.println(mUserVisibleHint);
1487        if (mFragmentManager != null) {
1488            writer.print(prefix); writer.print("mFragmentManager=");
1489                    writer.println(mFragmentManager);
1490        }
1491        if (mActivity != null) {
1492            writer.print(prefix); writer.print("mActivity=");
1493                    writer.println(mActivity);
1494        }
1495        if (mArguments != null) {
1496            writer.print(prefix); writer.print("mArguments="); writer.println(mArguments);
1497        }
1498        if (mSavedFragmentState != null) {
1499            writer.print(prefix); writer.print("mSavedFragmentState=");
1500                    writer.println(mSavedFragmentState);
1501        }
1502        if (mSavedViewState != null) {
1503            writer.print(prefix); writer.print("mSavedViewState=");
1504                    writer.println(mSavedViewState);
1505        }
1506        if (mTarget != null) {
1507            writer.print(prefix); writer.print("mTarget="); writer.print(mTarget);
1508                    writer.print(" mTargetRequestCode=");
1509                    writer.println(mTargetRequestCode);
1510        }
1511        if (mNextAnim != 0) {
1512            writer.print(prefix); writer.print("mNextAnim="); writer.println(mNextAnim);
1513        }
1514        if (mContainer != null) {
1515            writer.print(prefix); writer.print("mContainer="); writer.println(mContainer);
1516        }
1517        if (mView != null) {
1518            writer.print(prefix); writer.print("mView="); writer.println(mView);
1519        }
1520        if (mAnimatingAway != null) {
1521            writer.print(prefix); writer.print("mAnimatingAway="); writer.println(mAnimatingAway);
1522            writer.print(prefix); writer.print("mStateAfterAnimating=");
1523                    writer.println(mStateAfterAnimating);
1524        }
1525        if (mLoaderManager != null) {
1526            writer.print(prefix); writer.println("Loader Manager:");
1527            mLoaderManager.dump(prefix + "  ", fd, writer, args);
1528        }
1529    }
1530
1531    void performStart() {
1532        onStart();
1533        if (mLoaderManager != null) {
1534            mLoaderManager.doReportStart();
1535        }
1536    }
1537
1538    void performStop() {
1539        onStop();
1540
1541        if (mLoadersStarted) {
1542            mLoadersStarted = false;
1543            if (!mCheckedForLoaderManager) {
1544                mCheckedForLoaderManager = true;
1545                mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
1546            }
1547            if (mLoaderManager != null) {
1548                if (mActivity == null || !mActivity.mChangingConfigurations) {
1549                    mLoaderManager.doStop();
1550                } else {
1551                    mLoaderManager.doRetain();
1552                }
1553            }
1554        }
1555    }
1556
1557    void performDestroyView() {
1558        onDestroyView();
1559        if (mLoaderManager != null) {
1560            mLoaderManager.doReportNextStart();
1561        }
1562    }
1563}
1564