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