Fragment.java revision 9277b9e4419c1f0b5236d9b573a7cc0b23d56402
1/*
2 * Copyright (C) 2011 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.support.v4.app;
18
19import android.app.Activity;
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.support.v4.util.DebugUtils;
29import android.util.AttributeSet;
30import android.util.SparseArray;
31import android.view.ContextMenu;
32import android.view.LayoutInflater;
33import android.view.Menu;
34import android.view.MenuInflater;
35import android.view.MenuItem;
36import android.view.View;
37import android.view.ViewGroup;
38import android.view.ContextMenu.ContextMenuInfo;
39import android.view.View.OnCreateContextMenuListener;
40import android.view.animation.Animation;
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 Bundle mArguments;
56
57    Bundle mSavedFragmentState;
58
59    Fragment mInstance;
60
61    public FragmentState(Fragment frag) {
62        mClassName = frag.getClass().getName();
63        mIndex = frag.mIndex;
64        mFromLayout = frag.mFromLayout;
65        mFragmentId = frag.mFragmentId;
66        mContainerId = frag.mContainerId;
67        mTag = frag.mTag;
68        mRetainInstance = frag.mRetainInstance;
69        mArguments = frag.mArguments;
70    }
71
72    public FragmentState(Parcel in) {
73        mClassName = in.readString();
74        mIndex = in.readInt();
75        mFromLayout = in.readInt() != 0;
76        mFragmentId = in.readInt();
77        mContainerId = in.readInt();
78        mTag = in.readString();
79        mRetainInstance = in.readInt() != 0;
80        mArguments = in.readBundle();
81        mSavedFragmentState = in.readBundle();
82    }
83
84    public Fragment instantiate(FragmentActivity activity) {
85        if (mInstance != null) {
86            return mInstance;
87        }
88
89        if (mArguments != null) {
90            mArguments.setClassLoader(activity.getClassLoader());
91        }
92
93        mInstance = Fragment.instantiate(activity, mClassName, mArguments);
94
95        if (mSavedFragmentState != null) {
96            mSavedFragmentState.setClassLoader(activity.getClassLoader());
97            mInstance.mSavedFragmentState = mSavedFragmentState;
98        }
99        mInstance.setIndex(mIndex);
100        mInstance.mFromLayout = mFromLayout;
101        mInstance.mRestored = true;
102        mInstance.mFragmentId = mFragmentId;
103        mInstance.mContainerId = mContainerId;
104        mInstance.mTag = mTag;
105        mInstance.mRetainInstance = mRetainInstance;
106        mInstance.mFragmentManager = activity.mFragments;
107
108        return mInstance;
109    }
110
111    public int describeContents() {
112        return 0;
113    }
114
115    public void writeToParcel(Parcel dest, int flags) {
116        dest.writeString(mClassName);
117        dest.writeInt(mIndex);
118        dest.writeInt(mFromLayout ? 1 : 0);
119        dest.writeInt(mFragmentId);
120        dest.writeInt(mContainerId);
121        dest.writeString(mTag);
122        dest.writeInt(mRetainInstance ? 1 : 0);
123        dest.writeBundle(mArguments);
124        dest.writeBundle(mSavedFragmentState);
125    }
126
127    public static final Parcelable.Creator<FragmentState> CREATOR
128            = new Parcelable.Creator<FragmentState>() {
129        public FragmentState createFromParcel(Parcel in) {
130            return new FragmentState(in);
131        }
132
133        public FragmentState[] newArray(int size) {
134            return new FragmentState[size];
135        }
136    };
137}
138
139/**
140 * Static library support version of the framework's {@link android.app.Fragment}.
141 * Used to write apps that run on platforms prior to Android 3.0.  When running
142 * on Android 3.0 or above, this implementation is still used; it does not try
143 * to switch to the framework's implementation.  See the framework SDK
144 * documentation for a class overview.
145 */
146public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener {
147    private static final HashMap<String, Class<?>> sClassMap =
148            new HashMap<String, Class<?>>();
149
150    static final int INITIALIZING = 0;     // Not yet created.
151    static final int CREATED = 1;          // Created.
152    static final int ACTIVITY_CREATED = 2; // The activity has finished its creation.
153    static final int STARTED = 3;          // Created and started, not resumed.
154    static final int RESUMED = 4;          // Created started and resumed.
155
156    int mState = INITIALIZING;
157
158    // Non-null if the fragment's view hierarchy is currently animating away,
159    // meaning we need to wait a bit on completely destroying it.  This is the
160    // view that is animating.
161    View mAnimatingAway;
162
163    // If mAnimatingAway != null, this is the state we should move to once the
164    // animation is done.
165    int mStateAfterAnimating;
166
167    // When instantiated from saved state, this is the saved state.
168    Bundle mSavedFragmentState;
169    SparseArray<Parcelable> mSavedViewState;
170
171    // Index into active fragment array.
172    int mIndex = -1;
173
174    // Internal unique name for this fragment;
175    String mWho;
176
177    // Construction arguments;
178    Bundle mArguments;
179
180    // Target fragment.
181    Fragment mTarget;
182
183    // Target request code.
184    int mTargetRequestCode;
185
186    // True if the fragment is in the list of added fragments.
187    boolean mAdded;
188
189    // If set this fragment is being removed from its activity.
190    boolean mRemoving;
191
192    // True if the fragment is in the resumed state.
193    boolean mResumed;
194
195    // Set to true if this fragment was instantiated from a layout file.
196    boolean mFromLayout;
197
198    // Set to true when the view has actually been inflated in its layout.
199    boolean mInLayout;
200
201    // True if this fragment has been restored from previously saved state.
202    boolean mRestored;
203
204    // Number of active back stack entries this fragment is in.
205    int mBackStackNesting;
206
207    // The fragment manager we are associated with.  Set as soon as the
208    // fragment is used in a transaction; cleared after it has been removed
209    // from all transactions.
210    FragmentManager mFragmentManager;
211
212    // Set as soon as a fragment is added to a transaction (or removed),
213    // to be able to do validation.
214    FragmentActivity mImmediateActivity;
215
216    // Activity this fragment is attached to.
217    FragmentActivity mActivity;
218
219    // The optional identifier for this fragment -- either the container ID if it
220    // was dynamically added to the view hierarchy, or the ID supplied in
221    // layout.
222    int mFragmentId;
223
224    // When a fragment is being dynamically added to the view hierarchy, this
225    // is the identifier of the parent container it is being added to.
226    int mContainerId;
227
228    // The optional named tag for this fragment -- usually used to find
229    // fragments that are not part of the layout.
230    String mTag;
231
232    // Set to true when the app has requested that this fragment be hidden
233    // from the user.
234    boolean mHidden;
235
236    // If set this fragment would like its instance retained across
237    // configuration changes.
238    boolean mRetainInstance;
239
240    // If set this fragment is being retained across the current config change.
241    boolean mRetaining;
242
243    // If set this fragment has menu items to contribute.
244    boolean mHasMenu;
245
246    // Used to verify that subclasses call through to super class.
247    boolean mCalled;
248
249    // If app has requested a specific animation, this is the one to use.
250    int mNextAnim;
251
252    // The parent container of the fragment after dynamically added to UI.
253    ViewGroup mContainer;
254
255    // The View generated for this fragment.
256    View mView;
257
258    // The real inner view that will save/restore state.
259    View mInnerView;
260
261    LoaderManagerImpl mLoaderManager;
262    boolean mLoadersStarted;
263    boolean mCheckedForLoaderManager;
264
265    /**
266     * Thrown by {@link Fragment#instantiate(Context, String, Bundle)} when
267     * there is an instantiation failure.
268     */
269    static public class InstantiationException extends RuntimeException {
270        public InstantiationException(String msg, Exception cause) {
271            super(msg, cause);
272        }
273    }
274
275    /**
276     * Default constructor.  <strong>Every</strong> fragment must have an
277     * empty constructor, so it can be instantiated when restoring its
278     * activity's state.  It is strongly recommended that subclasses do not
279     * have other constructors with parameters, since these constructors
280     * will not be called when the fragment is re-instantiated; instead,
281     * arguments can be supplied by the caller with {@link #setArguments}
282     * and later retrieved by the Fragment with {@link #getArguments}.
283     *
284     * <p>Applications should generally not implement a constructor.  The
285     * first place application code an run where the fragment is ready to
286     * be used is in {@link #onAttach(Activity)}, the point where the fragment
287     * is actually associated with its activity.  Some applications may also
288     * want to implement {@link #onInflate} to retrieve attributes from a
289     * layout resource, though should take care here because this happens for
290     * the fragment is attached to its activity.
291     */
292    public Fragment() {
293    }
294
295    /**
296     * Like {@link #instantiate(Context, String, Bundle)} but with a null
297     * argument Bundle.
298     */
299    public static Fragment instantiate(Context context, String fname) {
300        return instantiate(context, fname, null);
301    }
302
303    /**
304     * Create a new instance of a Fragment with the given class name.  This is
305     * the same as calling its empty constructor.
306     *
307     * @param context The calling context being used to instantiate the fragment.
308     * This is currently just used to get its ClassLoader.
309     * @param fname The class name of the fragment to instantiate.
310     * @param args Bundle of arguments to supply to the fragment, which it
311     * can retrieve with {@link #getArguments()}.  May be null.
312     * @return Returns a new fragment instance.
313     * @throws InstantiationException If there is a failure in instantiating
314     * the given fragment class.  This is a runtime exception; it is not
315     * normally expected to happen.
316     */
317    public static Fragment instantiate(Context context, String fname, Bundle args) {
318        try {
319            Class<?> clazz = sClassMap.get(fname);
320            if (clazz == null) {
321                // Class not found in the cache, see if it's real, and try to add it
322                clazz = context.getClassLoader().loadClass(fname);
323                sClassMap.put(fname, clazz);
324            }
325            Fragment f = (Fragment)clazz.newInstance();
326            if (args != null) {
327                args.setClassLoader(f.getClass().getClassLoader());
328                f.mArguments = args;
329            }
330            return f;
331        } catch (ClassNotFoundException e) {
332            throw new InstantiationException("Unable to instantiate fragment " + fname
333                    + ": make sure class name exists, is public, and has an"
334                    + " empty constructor that is public", e);
335        } catch (java.lang.InstantiationException e) {
336            throw new InstantiationException("Unable to instantiate fragment " + fname
337                    + ": make sure class name exists, is public, and has an"
338                    + " empty constructor that is public", e);
339        } catch (IllegalAccessException e) {
340            throw new InstantiationException("Unable to instantiate fragment " + fname
341                    + ": make sure class name exists, is public, and has an"
342                    + " empty constructor that is public", e);
343        }
344    }
345
346    void restoreViewState() {
347        if (mSavedViewState != null) {
348            mInnerView.restoreHierarchyState(mSavedViewState);
349            mSavedViewState = null;
350        }
351    }
352
353    void setIndex(int index) {
354        mIndex = index;
355        mWho = "android:fragment:" + mIndex;
356   }
357
358    void clearIndex() {
359        mIndex = -1;
360        mWho = null;
361    }
362
363    /**
364     * Subclasses can not override equals().
365     */
366    @Override final public boolean equals(Object o) {
367        return super.equals(o);
368    }
369
370    /**
371     * Subclasses can not override hashCode().
372     */
373    @Override final public int hashCode() {
374        return super.hashCode();
375    }
376
377    @Override
378    public String toString() {
379        StringBuilder sb = new StringBuilder(128);
380        DebugUtils.buildShortClassTag(this, sb);
381        if (mIndex >= 0) {
382            sb.append(" #");
383            sb.append(mIndex);
384        }
385        if (mFragmentId != 0) {
386            sb.append(" id=0x");
387            sb.append(Integer.toHexString(mFragmentId));
388        }
389        if (mTag != null) {
390            sb.append(" ");
391            sb.append(mTag);
392        }
393        sb.append('}');
394        return sb.toString();
395    }
396
397    /**
398     * Return the identifier this fragment is known by.  This is either
399     * the android:id value supplied in a layout or the container view ID
400     * supplied when adding the fragment.
401     */
402    final public int getId() {
403        return mFragmentId;
404    }
405
406    /**
407     * Get the tag name of the fragment, if specified.
408     */
409    final public String getTag() {
410        return mTag;
411    }
412
413    /**
414     * Supply the construction arguments for this fragment.  This can only
415     * be called before the fragment has been attached to its activity; that
416     * is, you should call it immediately after constructing the fragment.  The
417     * arguments supplied here will be retained across fragment destroy and
418     * creation.
419     */
420    public void setArguments(Bundle args) {
421        if (mIndex >= 0) {
422            throw new IllegalStateException("Fragment already active");
423        }
424        mArguments = args;
425    }
426
427    /**
428     * Return the arguments supplied when the fragment was instantiated,
429     * if any.
430     */
431    final public Bundle getArguments() {
432        return mArguments;
433    }
434
435    /**
436     * Optional target for this fragment.  This may be used, for example,
437     * if this fragment is being started by another, and when done wants to
438     * give a result back to the first.  The target set here is retained
439     * across instances via {@link FragmentManager#putFragment
440     * FragmentManager.putFragment()}.
441     *
442     * @param fragment The fragment that is the target of this one.
443     * @param requestCode Optional request code, for convenience if you
444     * are going to call back with {@link #onActivityResult(int, int, Intent)}.
445     */
446    public void setTargetFragment(Fragment fragment, int requestCode) {
447        mTarget = fragment;
448        mTargetRequestCode = requestCode;
449    }
450
451    /**
452     * Return the target fragment set by {@link #setTargetFragment}.
453     */
454    final public Fragment getTargetFragment() {
455        return mTarget;
456    }
457
458    /**
459     * Return the target request code set by {@link #setTargetFragment}.
460     */
461    final public int getTargetRequestCode() {
462        return mTargetRequestCode;
463    }
464
465    /**
466     * Return the Activity this fragment is currently associated with.
467     */
468    final public FragmentActivity getActivity() {
469        return mActivity;
470    }
471
472    /**
473     * Return <code>getActivity().getResources()</code>.
474     */
475    final public Resources getResources() {
476        if (mActivity == null) {
477            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
478        }
479        return mActivity.getResources();
480    }
481
482    /**
483     * Return a localized, styled CharSequence from the application's package's
484     * default string table.
485     *
486     * @param resId Resource id for the CharSequence text
487     */
488    public final CharSequence getText(int resId) {
489        return getResources().getText(resId);
490    }
491
492    /**
493     * Return a localized string from the application's package's
494     * default string table.
495     *
496     * @param resId Resource id for the string
497     */
498    public final String getString(int resId) {
499        return getResources().getString(resId);
500    }
501
502    /**
503     * Return a localized formatted string from the application's package's
504     * default string table, substituting the format arguments as defined in
505     * {@link java.util.Formatter} and {@link java.lang.String#format}.
506     *
507     * @param resId Resource id for the format string
508     * @param formatArgs The format arguments that will be used for substitution.
509     */
510
511    public final String getString(int resId, Object... formatArgs) {
512        return getResources().getString(resId, formatArgs);
513    }
514
515    /**
516     * Return the FragmentManager for interacting with fragments associated
517     * with this fragment's activity.  Note that this will be non-null slightly
518     * before {@link #getActivity()}, during the time from when the fragment is
519     * placed in a {@link FragmentTransaction} until it is committed and
520     * attached to its activity.
521     */
522    final public FragmentManager getFragmentManager() {
523        return mFragmentManager;
524    }
525
526    /**
527     * Return true if the fragment is currently added to its activity.
528     */
529    final public boolean isAdded() {
530        return mActivity != null && mAdded;
531    }
532
533    /**
534     * Return true if this fragment is currently being removed from its
535     * activity.  This is  <em>not</em> whether its activity is finishing, but
536     * rather whether it is in the process of being removed from its activity.
537     */
538    final public boolean isRemoving() {
539        return mRemoving;
540    }
541
542    /**
543     * Return true if the layout is included as part of an activity view
544     * hierarchy via the &lt;fragment&gt; tag.  This will always be true when
545     * fragments are created through the &lt;fragment&gt; tag, <em>except</em>
546     * in the case where an old fragment is restored from a previous state and
547     * it does not appear in the layout of the current state.
548     */
549    final public boolean isInLayout() {
550        return mInLayout;
551    }
552
553    /**
554     * Return true if the fragment is in the resumed state.  This is true
555     * for the duration of {@link #onResume()} and {@link #onPause()} as well.
556     */
557    final public boolean isResumed() {
558        return mResumed;
559    }
560
561    /**
562     * Return true if the fragment is currently visible to the user.  This means
563     * it: (1) has been added, (2) has its view attached to the window, and
564     * (3) is not hidden.
565     */
566    final public boolean isVisible() {
567        return isAdded() && !isHidden() && mView != null
568                && mView.getWindowToken() != null && mView.getVisibility() == View.VISIBLE;
569    }
570
571    /**
572     * Return true if the fragment has been hidden.  By default fragments
573     * are shown.  You can find out about changes to this state with
574     * {@link #onHiddenChanged}.  Note that the hidden state is orthogonal
575     * to other states -- that is, to be visible to the user, a fragment
576     * must be both started and not hidden.
577     */
578    final public boolean isHidden() {
579        return mHidden;
580    }
581
582    /**
583     * Called when the hidden state (as returned by {@link #isHidden()} of
584     * the fragment has changed.  Fragments start out not hidden; this will
585     * be called whenever the fragment changes state from that.
586     * @param hidden True if the fragment is now hidden, false if it is not
587     * visible.
588     */
589    public void onHiddenChanged(boolean hidden) {
590    }
591
592    /**
593     * Control whether a fragment instance is retained across Activity
594     * re-creation (such as from a configuration change).  This can only
595     * be used with fragments not in the back stack.  If set, the fragment
596     * lifecycle will be slightly different when an activity is recreated:
597     * <ul>
598     * <li> {@link #onDestroy()} will not be called (but {@link #onDetach()} still
599     * will be, because the fragment is being detached from its current activity).
600     * <li> {@link #onCreate(Bundle)} will not be called since the fragment
601     * is not being re-created.
602     * <li> {@link #onAttach(Activity)} and {@link #onActivityCreated(Bundle)} <b>will</b>
603     * still be called.
604     * </ul>
605     */
606    public void setRetainInstance(boolean retain) {
607        mRetainInstance = retain;
608    }
609
610    final public boolean getRetainInstance() {
611        return mRetainInstance;
612    }
613
614    /**
615     * Report that this fragment would like to participate in populating
616     * the options menu by receiving a call to {@link #onCreateOptionsMenu}
617     * and related methods.
618     *
619     * @param hasMenu If true, the fragment has menu items to contribute.
620     */
621    public void setHasOptionsMenu(boolean hasMenu) {
622        if (mHasMenu != hasMenu) {
623            mHasMenu = hasMenu;
624            if (isAdded() && !isHidden()) {
625                mActivity.supportInvalidateOptionsMenu();
626            }
627        }
628    }
629
630    /**
631     * Return the LoaderManager for this fragment, creating it if needed.
632     */
633    public LoaderManager getLoaderManager() {
634        if (mLoaderManager != null) {
635            return mLoaderManager;
636        }
637        if (mActivity == null) {
638            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
639        }
640        mCheckedForLoaderManager = true;
641        mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, true);
642        return mLoaderManager;
643    }
644
645    /**
646     * Call {@link Activity#startActivity(Intent)} on the fragment's
647     * containing Activity.
648     */
649    public void startActivity(Intent intent) {
650        if (mActivity == null) {
651            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
652        }
653        mActivity.startActivityFromFragment(this, intent, -1);
654    }
655
656    /**
657     * Call {@link Activity#startActivityForResult(Intent, int)} on the fragment's
658     * containing Activity.
659     */
660    public void startActivityForResult(Intent intent, int requestCode) {
661        if (mActivity == null) {
662            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
663        }
664        mActivity.startActivityFromFragment(this, intent, requestCode);
665    }
666
667    /**
668     * Receive the result from a previous call to
669     * {@link #startActivityForResult(Intent, int)}.  This follows the
670     * related Activity API as described there in
671     * {@link Activity#onActivityResult(int, int, Intent)}.
672     *
673     * @param requestCode The integer request code originally supplied to
674     *                    startActivityForResult(), allowing you to identify who this
675     *                    result came from.
676     * @param resultCode The integer result code returned by the child activity
677     *                   through its setResult().
678     * @param data An Intent, which can return result data to the caller
679     *               (various data can be attached to Intent "extras").
680     */
681    public void onActivityResult(int requestCode, int resultCode, Intent data) {
682    }
683
684    /**
685     * @hide Hack so that DialogFragment can make its Dialog before creating
686     * its views, and the view construction can use the dialog's context for
687     * inflation.  Maybe this should become a public API. Note sure.
688     */
689    public LayoutInflater getLayoutInflater(Bundle savedInstanceState) {
690        return mActivity.getLayoutInflater();
691    }
692
693    /**
694     * Called when a fragment is being created as part of a view layout
695     * inflation, typically from setting the content view of an activity.  This
696     * may be called immediately after the fragment is created from a <fragment>
697     * tag in a layout file.  Note this is <em>before</em> the fragment's
698     * {@link #onAttach(Activity)} has been called; all you should do here is
699     * parse the attributes and save them away.
700     *
701     * <p>This is called every time the fragment is inflated, even if it is
702     * being inflated into a new instance with saved state.  It typically makes
703     * sense to re-parse the parameters each time, to allow them to change with
704     * different configurations.</p>
705     *
706     * <p>Here is a typical implementation of a fragment that can take parameters
707     * both through attributes supplied here as well from {@link #getArguments()}:</p>
708     *
709     * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
710     *      fragment}
711     *
712     * <p>Note that parsing the XML attributes uses a "styleable" resource.  The
713     * declaration for the styleable used here is:</p>
714     *
715     * {@sample development/samples/ApiDemos/res/values/attrs.xml fragment_arguments}
716     *
717     * <p>The fragment can then be declared within its activity's content layout
718     * through a tag like this:</p>
719     *
720     * {@sample development/samples/ApiDemos/res/layout/fragment_arguments.xml from_attributes}
721     *
722     * <p>This fragment can also be created dynamically from arguments given
723     * at runtime in the arguments Bundle; here is an example of doing so at
724     * creation of the containing activity:</p>
725     *
726     * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
727     *      create}
728     *
729     * @param activity The Activity that is inflating this fragment.
730     * @param attrs The attributes at the tag where the fragment is
731     * being created.
732     * @param savedInstanceState If the fragment is being re-created from
733     * a previous saved state, this is the state.
734     */
735    public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
736        mCalled = true;
737    }
738
739    /**
740     * Called when a fragment is first attached to its activity.
741     * {@link #onCreate(Bundle)} will be called after this.
742     */
743    public void onAttach(Activity activity) {
744        mCalled = true;
745    }
746
747    /**
748     * Called when a fragment loads an animation.
749     */
750    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
751        return null;
752    }
753
754    /**
755     * Called to do initial creation of a fragment.  This is called after
756     * {@link #onAttach(Activity)} and before
757     * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
758     *
759     * <p>Note that this can be called while the fragment's activity is
760     * still in the process of being created.  As such, you can not rely
761     * on things like the activity's content view hierarchy being initialized
762     * at this point.  If you want to do work once the activity itself is
763     * created, see {@link #onActivityCreated(Bundle)}.
764     *
765     * @param savedInstanceState If the fragment is being re-created from
766     * a previous saved state, this is the state.
767     */
768    public void onCreate(Bundle savedInstanceState) {
769        mCalled = true;
770    }
771
772    /**
773     * Called to have the fragment instantiate its user interface view.
774     * This is optional, and non-graphical fragments can return null (which
775     * is the default implementation).  This will be called between
776     * {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}.
777     *
778     * <p>If you return a View from here, you will later be called in
779     * {@link #onDestroyView} when the view is being released.
780     *
781     * @param inflater The LayoutInflater object that can be used to inflate
782     * any views in the fragment,
783     * @param container If non-null, this is the parent view that the fragment's
784     * UI should be attached to.  The fragment should not add the view itself,
785     * but this can be used to generate the LayoutParams of the view.
786     * @param savedInstanceState If non-null, this fragment is being re-constructed
787     * from a previous saved state as given here.
788     *
789     * @return Return the View for the fragment's UI, or null.
790     */
791    public View onCreateView(LayoutInflater inflater, ViewGroup container,
792            Bundle savedInstanceState) {
793        return null;
794    }
795
796    /**
797     * Get the root view for the fragment's layout (the one returned by {@link #onCreateView}),
798     * if provided.
799     *
800     * @return The fragment's root view, or null if it has no layout.
801     */
802    public View getView() {
803        return mView;
804    }
805
806    /**
807     * Called when the fragment's activity has been created and this
808     * fragment's view hierarchy instantiated.  It can be used to do final
809     * initialization once these pieces are in place, such as retrieving
810     * views or restoring state.  It is also useful for fragments that use
811     * {@link #setRetainInstance(boolean)} to retain their instance,
812     * as this callback tells the fragment when it is fully associated with
813     * the new activity instance.  This is called after {@link #onCreateView}
814     * and before {@link #onStart()}.
815     *
816     * @param savedInstanceState If the fragment is being re-created from
817     * a previous saved state, this is the state.
818     */
819    public void onActivityCreated(Bundle savedInstanceState) {
820        mCalled = true;
821    }
822
823    /**
824     * Called when the Fragment is visible to the user.  This is generally
825     * tied to {@link Activity#onStart() Activity.onStart} of the containing
826     * Activity's lifecycle.
827     */
828    public void onStart() {
829        mCalled = true;
830
831        if (!mLoadersStarted) {
832            mLoadersStarted = true;
833            if (!mCheckedForLoaderManager) {
834                mCheckedForLoaderManager = true;
835                mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
836            }
837            if (mLoaderManager != null) {
838                mLoaderManager.doStart();
839            }
840        }
841    }
842
843    /**
844     * Called when the fragment is visible to the user and actively running.
845     * This is generally
846     * tied to {@link Activity#onResume() Activity.onResume} of the containing
847     * Activity's lifecycle.
848     */
849    public void onResume() {
850        mCalled = true;
851    }
852
853    /**
854     * Called to ask the fragment to save its current dynamic state, so it
855     * can later be reconstructed in a new instance of its process is
856     * restarted.  If a new instance of the fragment later needs to be
857     * created, the data you place in the Bundle here will be available
858     * in the Bundle given to {@link #onCreate(Bundle)},
859     * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}, and
860     * {@link #onActivityCreated(Bundle)}.
861     *
862     * <p>This corresponds to {@link Activity#onSaveInstanceState(Bundle)
863     * Activity.onSaveInstanceState(Bundle)} and most of the discussion there
864     * applies here as well.  Note however: <em>this method may be called
865     * at any time before {@link #onDestroy()}</em>.  There are many situations
866     * where a fragment may be mostly torn down (such as when placed on the
867     * back stack with no UI showing), but its state will not be saved until
868     * its owning activity actually needs to save its state.
869     *
870     * @param outState Bundle in which to place your saved state.
871     */
872    public void onSaveInstanceState(Bundle outState) {
873    }
874
875    public void onConfigurationChanged(Configuration newConfig) {
876        mCalled = true;
877    }
878
879    /**
880     * Called when the Fragment is no longer resumed.  This is generally
881     * tied to {@link Activity#onPause() Activity.onPause} of the containing
882     * Activity's lifecycle.
883     */
884    public void onPause() {
885        mCalled = true;
886    }
887
888    /**
889     * Called when the Fragment is no longer started.  This is generally
890     * tied to {@link Activity#onStop() Activity.onStop} of the containing
891     * Activity's lifecycle.
892     */
893    public void onStop() {
894        mCalled = true;
895    }
896
897    public void onLowMemory() {
898        mCalled = true;
899    }
900
901    /**
902     * Called when the view previously created by {@link #onCreateView} has
903     * been detached from the fragment.  The next time the fragment needs
904     * to be displayed, a new view will be created.  This is called
905     * after {@link #onStop()} and before {@link #onDestroy()}.  It is called
906     * <em>regardless</em> of whether {@link #onCreateView} returned a
907     * non-null view.  Internally it is called after the view's state has
908     * been saved but before it has been removed from its parent.
909     */
910    public void onDestroyView() {
911        mCalled = true;
912    }
913
914    /**
915     * Called when the fragment is no longer in use.  This is called
916     * after {@link #onStop()} and before {@link #onDetach()}.
917     */
918    public void onDestroy() {
919        mCalled = true;
920        //Log.v("foo", "onDestroy: mCheckedForLoaderManager=" + mCheckedForLoaderManager
921        //        + " mLoaderManager=" + mLoaderManager);
922        if (!mCheckedForLoaderManager) {
923            mCheckedForLoaderManager = true;
924            mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
925        }
926        if (mLoaderManager != null) {
927            mLoaderManager.doDestroy();
928        }
929    }
930
931    /**
932     * Called when the fragment is no longer attached to its activity.  This
933     * is called after {@link #onDestroy()}.
934     */
935    public void onDetach() {
936        mCalled = true;
937    }
938
939    /**
940     * Initialize the contents of the Activity's standard options menu.  You
941     * should place your menu items in to <var>menu</var>.  For this method
942     * to be called, you must have first called {@link #setHasOptionsMenu}.  See
943     * {@link Activity#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu}
944     * for more information.
945     *
946     * @param menu The options menu in which you place your items.
947     *
948     * @see #setHasOptionsMenu
949     * @see #onPrepareOptionsMenu
950     * @see #onOptionsItemSelected
951     */
952    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
953    }
954
955    /**
956     * Prepare the Screen's standard options menu to be displayed.  This is
957     * called right before the menu is shown, every time it is shown.  You can
958     * use this method to efficiently enable/disable items or otherwise
959     * dynamically modify the contents.  See
960     * {@link Activity#onPrepareOptionsMenu(Menu) Activity.onPrepareOptionsMenu}
961     * for more information.
962     *
963     * @param menu The options menu as last shown or first initialized by
964     *             onCreateOptionsMenu().
965     *
966     * @see #setHasOptionsMenu
967     * @see #onCreateOptionsMenu
968     */
969    public void onPrepareOptionsMenu(Menu menu) {
970    }
971
972    /**
973     * Called when this fragment's option menu items are no longer being
974     * included in the overall options menu.  Receiving this call means that
975     * the menu needed to be rebuilt, but this fragment's items were not
976     * included in the newly built menu (its {@link #onCreateOptionsMenu(Menu, MenuInflater)}
977     * was not called).
978     */
979    public void onDestroyOptionsMenu() {
980    }
981
982    /**
983     * This hook is called whenever an item in your options menu is selected.
984     * The default implementation simply returns false to have the normal
985     * processing happen (calling the item's Runnable or sending a message to
986     * its Handler as appropriate).  You can use this method for any items
987     * for which you would like to do processing without those other
988     * facilities.
989     *
990     * <p>Derived classes should call through to the base class for it to
991     * perform the default menu handling.
992     *
993     * @param item The menu item that was selected.
994     *
995     * @return boolean Return false to allow normal menu processing to
996     *         proceed, true to consume it here.
997     *
998     * @see #onCreateOptionsMenu
999     */
1000    public boolean onOptionsItemSelected(MenuItem item) {
1001        return false;
1002    }
1003
1004    /**
1005     * This hook is called whenever the options menu is being closed (either by the user canceling
1006     * the menu with the back/menu button, or when an item is selected).
1007     *
1008     * @param menu The options menu as last shown or first initialized by
1009     *             onCreateOptionsMenu().
1010     */
1011    public void onOptionsMenuClosed(Menu menu) {
1012    }
1013
1014    /**
1015     * Called when a context menu for the {@code view} is about to be shown.
1016     * Unlike {@link #onCreateOptionsMenu}, this will be called every
1017     * time the context menu is about to be shown and should be populated for
1018     * the view (or item inside the view for {@link AdapterView} subclasses,
1019     * this can be found in the {@code menuInfo})).
1020     * <p>
1021     * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
1022     * item has been selected.
1023     * <p>
1024     * The default implementation calls up to
1025     * {@link Activity#onCreateContextMenu Activity.onCreateContextMenu}, though
1026     * you can not call this implementation if you don't want that behavior.
1027     * <p>
1028     * It is not safe to hold onto the context menu after this method returns.
1029     * {@inheritDoc}
1030     */
1031    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1032        getActivity().onCreateContextMenu(menu, v, menuInfo);
1033    }
1034
1035    /**
1036     * Registers a context menu to be shown for the given view (multiple views
1037     * can show the context menu). This method will set the
1038     * {@link OnCreateContextMenuListener} on the view to this fragment, so
1039     * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
1040     * called when it is time to show the context menu.
1041     *
1042     * @see #unregisterForContextMenu(View)
1043     * @param view The view that should show a context menu.
1044     */
1045    public void registerForContextMenu(View view) {
1046        view.setOnCreateContextMenuListener(this);
1047    }
1048
1049    /**
1050     * Prevents a context menu to be shown for the given view. This method will
1051     * remove the {@link OnCreateContextMenuListener} on the view.
1052     *
1053     * @see #registerForContextMenu(View)
1054     * @param view The view that should stop showing a context menu.
1055     */
1056    public void unregisterForContextMenu(View view) {
1057        view.setOnCreateContextMenuListener(null);
1058    }
1059
1060    /**
1061     * This hook is called whenever an item in a context menu is selected. The
1062     * default implementation simply returns false to have the normal processing
1063     * happen (calling the item's Runnable or sending a message to its Handler
1064     * as appropriate). You can use this method for any items for which you
1065     * would like to do processing without those other facilities.
1066     * <p>
1067     * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
1068     * View that added this menu item.
1069     * <p>
1070     * Derived classes should call through to the base class for it to perform
1071     * the default menu handling.
1072     *
1073     * @param item The context menu item that was selected.
1074     * @return boolean Return false to allow normal context menu processing to
1075     *         proceed, true to consume it here.
1076     */
1077    public boolean onContextItemSelected(MenuItem item) {
1078        return false;
1079    }
1080
1081    /**
1082     * Print the Fragments's state into the given stream.
1083     *
1084     * @param prefix Text to print at the front of each line.
1085     * @param fd The raw file descriptor that the dump is being sent to.
1086     * @param writer The PrintWriter to which you should dump your state.  This will be
1087     * closed for you after you return.
1088     * @param args additional arguments to the dump request.
1089     */
1090    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
1091        writer.print(prefix); writer.print("mFragmentId=#");
1092                writer.print(Integer.toHexString(mFragmentId));
1093                writer.print(" mContainerId#=");
1094                writer.print(Integer.toHexString(mContainerId));
1095                writer.print(" mTag="); writer.println(mTag);
1096        writer.print(prefix); writer.print("mState="); writer.print(mState);
1097                writer.print(" mIndex="); writer.print(mIndex);
1098                writer.print(" mWho="); writer.print(mWho);
1099                writer.print(" mBackStackNesting="); writer.println(mBackStackNesting);
1100        writer.print(prefix); writer.print("mAdded="); writer.print(mAdded);
1101                writer.print(" mRemoving="); writer.print(mRemoving);
1102                writer.print(" mResumed="); writer.print(mResumed);
1103                writer.print(" mFromLayout="); writer.print(mFromLayout);
1104                writer.print(" mInLayout="); writer.println(mInLayout);
1105        writer.print(prefix); writer.print("mHidden="); writer.print(mHidden);
1106                writer.print(" mRetainInstance="); writer.print(mRetainInstance);
1107                writer.print(" mRetaining="); writer.print(mRetaining);
1108                writer.print(" mHasMenu="); writer.println(mHasMenu);
1109        if (mFragmentManager != null) {
1110            writer.print(prefix); writer.print("mFragmentManager=");
1111                    writer.println(mFragmentManager);
1112        }
1113        if (mImmediateActivity != null) {
1114            writer.print(prefix); writer.print("mImmediateActivity=");
1115                    writer.println(mImmediateActivity);
1116        }
1117        if (mActivity != null) {
1118            writer.print(prefix); writer.print("mActivity=");
1119                    writer.println(mActivity);
1120        }
1121        if (mArguments != null) {
1122            writer.print(prefix); writer.print("mArguments="); writer.println(mArguments);
1123        }
1124        if (mSavedFragmentState != null) {
1125            writer.print(prefix); writer.print("mSavedFragmentState=");
1126                    writer.println(mSavedFragmentState);
1127        }
1128        if (mSavedViewState != null) {
1129            writer.print(prefix); writer.print("mSavedViewState=");
1130                    writer.println(mSavedViewState);
1131        }
1132        if (mTarget != null) {
1133            writer.print(prefix); writer.print("mTarget="); writer.print(mTarget);
1134                    writer.print(" mTargetRequestCode=");
1135                    writer.println(mTargetRequestCode);
1136        }
1137        if (mNextAnim != 0) {
1138            writer.print(prefix); writer.print("mNextAnim="); writer.println(mNextAnim);
1139        }
1140        if (mContainer != null) {
1141            writer.print(prefix); writer.print("mContainer="); writer.println(mContainer);
1142        }
1143        if (mView != null) {
1144            writer.print(prefix); writer.print("mView="); writer.println(mView);
1145        }
1146        if (mInnerView != null) {
1147            writer.print(prefix); writer.print("mInnerView="); writer.println(mView);
1148        }
1149        if (mAnimatingAway != null) {
1150            writer.print(prefix); writer.print("mAnimatingAway="); writer.println(mAnimatingAway);
1151            writer.print(prefix); writer.print("mStateAfterAnimating=");
1152                    writer.println(mStateAfterAnimating);
1153        }
1154        if (mLoaderManager != null) {
1155            writer.print(prefix); writer.println("Loader Manager:");
1156            mLoaderManager.dump(prefix + "  ", fd, writer, args);
1157        }
1158    }
1159
1160    void performStop() {
1161        onStop();
1162    }
1163
1164    void performReallyStop(boolean retaining) {
1165        if (mLoadersStarted) {
1166            mLoadersStarted = false;
1167            if (!mCheckedForLoaderManager) {
1168                mCheckedForLoaderManager = true;
1169                mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
1170            }
1171            if (mLoaderManager != null) {
1172                if (!retaining) {
1173                    mLoaderManager.doStop();
1174                } else {
1175                    mLoaderManager.doRetain();
1176                }
1177            }
1178        }
1179    }
1180}
1181