Fragment.java revision e3a7f628c6d9fef42be24999b3137ebe5c6f3525
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     * @hide Hack so that DialogFragment can make its Dialog before creating
854     * its views, and the view construction can use the dialog's context for
855     * inflation.  Maybe this should become a public API. Note sure.
856     */
857    public LayoutInflater getLayoutInflater(Bundle savedInstanceState) {
858        return mActivity.getLayoutInflater();
859    }
860
861    /**
862     * @deprecated Use {@link #onInflate(Activity, AttributeSet, Bundle)} instead.
863     */
864    @Deprecated
865    public void onInflate(AttributeSet attrs, Bundle savedInstanceState) {
866        mCalled = true;
867    }
868
869    /**
870     * Called when a fragment is being created as part of a view layout
871     * inflation, typically from setting the content view of an activity.  This
872     * may be called immediately after the fragment is created from a <fragment>
873     * tag in a layout file.  Note this is <em>before</em> the fragment's
874     * {@link #onAttach(Activity)} has been called; all you should do here is
875     * parse the attributes and save them away.
876     *
877     * <p>This is called every time the fragment is inflated, even if it is
878     * being inflated into a new instance with saved state.  It typically makes
879     * sense to re-parse the parameters each time, to allow them to change with
880     * different configurations.</p>
881     *
882     * <p>Here is a typical implementation of a fragment that can take parameters
883     * both through attributes supplied here as well from {@link #getArguments()}:</p>
884     *
885     * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
886     *      fragment}
887     *
888     * <p>Note that parsing the XML attributes uses a "styleable" resource.  The
889     * declaration for the styleable used here is:</p>
890     *
891     * {@sample development/samples/ApiDemos/res/values/attrs.xml fragment_arguments}
892     *
893     * <p>The fragment can then be declared within its activity's content layout
894     * through a tag like this:</p>
895     *
896     * {@sample development/samples/ApiDemos/res/layout/fragment_arguments.xml from_attributes}
897     *
898     * <p>This fragment can also be created dynamically from arguments given
899     * at runtime in the arguments Bundle; here is an example of doing so at
900     * creation of the containing activity:</p>
901     *
902     * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
903     *      create}
904     *
905     * @param activity The Activity that is inflating this fragment.
906     * @param attrs The attributes at the tag where the fragment is
907     * being created.
908     * @param savedInstanceState If the fragment is being re-created from
909     * a previous saved state, this is the state.
910     */
911    public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
912        onInflate(attrs, savedInstanceState);
913        mCalled = true;
914    }
915
916    /**
917     * Called when a fragment is first attached to its activity.
918     * {@link #onCreate(Bundle)} will be called after this.
919     */
920    public void onAttach(Activity activity) {
921        mCalled = true;
922    }
923
924    /**
925     * Called when a fragment loads an animation.
926     */
927    public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) {
928        return null;
929    }
930
931    /**
932     * Called to do initial creation of a fragment.  This is called after
933     * {@link #onAttach(Activity)} and before
934     * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
935     *
936     * <p>Note that this can be called while the fragment's activity is
937     * still in the process of being created.  As such, you can not rely
938     * on things like the activity's content view hierarchy being initialized
939     * at this point.  If you want to do work once the activity itself is
940     * created, see {@link #onActivityCreated(Bundle)}.
941     *
942     * @param savedInstanceState If the fragment is being re-created from
943     * a previous saved state, this is the state.
944     */
945    public void onCreate(Bundle savedInstanceState) {
946        mCalled = true;
947    }
948
949    /**
950     * Called to have the fragment instantiate its user interface view.
951     * This is optional, and non-graphical fragments can return null (which
952     * is the default implementation).  This will be called between
953     * {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}.
954     *
955     * <p>If you return a View from here, you will later be called in
956     * {@link #onDestroyView} when the view is being released.
957     *
958     * @param inflater The LayoutInflater object that can be used to inflate
959     * any views in the fragment,
960     * @param container If non-null, this is the parent view that the fragment's
961     * UI should be attached to.  The fragment should not add the view itself,
962     * but this can be used to generate the LayoutParams of the view.
963     * @param savedInstanceState If non-null, this fragment is being re-constructed
964     * from a previous saved state as given here.
965     *
966     * @return Return the View for the fragment's UI, or null.
967     */
968    public View onCreateView(LayoutInflater inflater, ViewGroup container,
969            Bundle savedInstanceState) {
970        return null;
971    }
972
973    /**
974     * Get the root view for the fragment's layout (the one returned by {@link #onCreateView}),
975     * if provided.
976     *
977     * @return The fragment's root view, or null if it has no layout.
978     */
979    public View getView() {
980        return mView;
981    }
982
983    /**
984     * Called when the fragment's activity has been created and this
985     * fragment's view hierarchy instantiated.  It can be used to do final
986     * initialization once these pieces are in place, such as retrieving
987     * views or restoring state.  It is also useful for fragments that use
988     * {@link #setRetainInstance(boolean)} to retain their instance,
989     * as this callback tells the fragment when it is fully associated with
990     * the new activity instance.  This is called after {@link #onCreateView}
991     * and before {@link #onStart()}.
992     *
993     * @param savedInstanceState If the fragment is being re-created from
994     * a previous saved state, this is the state.
995     */
996    public void onActivityCreated(Bundle savedInstanceState) {
997        mCalled = true;
998    }
999
1000    /**
1001     * Called when the Fragment is visible to the user.  This is generally
1002     * tied to {@link Activity#onStart() Activity.onStart} of the containing
1003     * Activity's lifecycle.
1004     */
1005    public void onStart() {
1006        mCalled = true;
1007
1008        if (!mLoadersStarted) {
1009            mLoadersStarted = true;
1010            if (!mCheckedForLoaderManager) {
1011                mCheckedForLoaderManager = true;
1012                mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
1013            }
1014            if (mLoaderManager != null) {
1015                mLoaderManager.doStart();
1016            }
1017        }
1018    }
1019
1020    /**
1021     * Called when the fragment is visible to the user and actively running.
1022     * This is generally
1023     * tied to {@link Activity#onResume() Activity.onResume} of the containing
1024     * Activity's lifecycle.
1025     */
1026    public void onResume() {
1027        mCalled = true;
1028    }
1029
1030    /**
1031     * Called to ask the fragment to save its current dynamic state, so it
1032     * can later be reconstructed in a new instance of its process is
1033     * restarted.  If a new instance of the fragment later needs to be
1034     * created, the data you place in the Bundle here will be available
1035     * in the Bundle given to {@link #onCreate(Bundle)},
1036     * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}, and
1037     * {@link #onActivityCreated(Bundle)}.
1038     *
1039     * <p>This corresponds to {@link Activity#onSaveInstanceState(Bundle)
1040     * Activity.onSaveInstanceState(Bundle)} and most of the discussion there
1041     * applies here as well.  Note however: <em>this method may be called
1042     * at any time before {@link #onDestroy()}</em>.  There are many situations
1043     * where a fragment may be mostly torn down (such as when placed on the
1044     * back stack with no UI showing), but its state will not be saved until
1045     * its owning activity actually needs to save its state.
1046     *
1047     * @param outState Bundle in which to place your saved state.
1048     */
1049    public void onSaveInstanceState(Bundle outState) {
1050    }
1051
1052    public void onConfigurationChanged(Configuration newConfig) {
1053        mCalled = true;
1054    }
1055
1056    /**
1057     * Called when the Fragment is no longer resumed.  This is generally
1058     * tied to {@link Activity#onPause() Activity.onPause} of the containing
1059     * Activity's lifecycle.
1060     */
1061    public void onPause() {
1062        mCalled = true;
1063    }
1064
1065    /**
1066     * Called when the Fragment is no longer started.  This is generally
1067     * tied to {@link Activity#onStop() Activity.onStop} of the containing
1068     * Activity's lifecycle.
1069     */
1070    public void onStop() {
1071        mCalled = true;
1072    }
1073
1074    public void onLowMemory() {
1075        mCalled = true;
1076    }
1077
1078    /**
1079     * Called when the view previously created by {@link #onCreateView} has
1080     * been detached from the fragment.  The next time the fragment needs
1081     * to be displayed, a new view will be created.  This is called
1082     * after {@link #onStop()} and before {@link #onDestroy()}.  It is called
1083     * <em>regardless</em> of whether {@link #onCreateView} returned a
1084     * non-null view.  Internally it is called after the view's state has
1085     * been saved but before it has been removed from its parent.
1086     */
1087    public void onDestroyView() {
1088        mCalled = true;
1089    }
1090
1091    /**
1092     * Called when the fragment is no longer in use.  This is called
1093     * after {@link #onStop()} and before {@link #onDetach()}.
1094     */
1095    public void onDestroy() {
1096        mCalled = true;
1097        //Log.v("foo", "onDestroy: mCheckedForLoaderManager=" + mCheckedForLoaderManager
1098        //        + " mLoaderManager=" + mLoaderManager);
1099        if (!mCheckedForLoaderManager) {
1100            mCheckedForLoaderManager = true;
1101            mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
1102        }
1103        if (mLoaderManager != null) {
1104            mLoaderManager.doDestroy();
1105        }
1106    }
1107
1108    /**
1109     * Called when the fragment is no longer attached to its activity.  This
1110     * is called after {@link #onDestroy()}.
1111     */
1112    public void onDetach() {
1113        mCalled = true;
1114    }
1115
1116    /**
1117     * Initialize the contents of the Activity's standard options menu.  You
1118     * should place your menu items in to <var>menu</var>.  For this method
1119     * to be called, you must have first called {@link #setHasOptionsMenu}.  See
1120     * {@link Activity#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu}
1121     * for more information.
1122     *
1123     * @param menu The options menu in which you place your items.
1124     *
1125     * @see #setHasOptionsMenu
1126     * @see #onPrepareOptionsMenu
1127     * @see #onOptionsItemSelected
1128     */
1129    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
1130    }
1131
1132    /**
1133     * Prepare the Screen's standard options menu to be displayed.  This is
1134     * called right before the menu is shown, every time it is shown.  You can
1135     * use this method to efficiently enable/disable items or otherwise
1136     * dynamically modify the contents.  See
1137     * {@link Activity#onPrepareOptionsMenu(Menu) Activity.onPrepareOptionsMenu}
1138     * for more information.
1139     *
1140     * @param menu The options menu as last shown or first initialized by
1141     *             onCreateOptionsMenu().
1142     *
1143     * @see #setHasOptionsMenu
1144     * @see #onCreateOptionsMenu
1145     */
1146    public void onPrepareOptionsMenu(Menu menu) {
1147    }
1148
1149    /**
1150     * Called when this fragment's option menu items are no longer being
1151     * included in the overall options menu.  Receiving this call means that
1152     * the menu needed to be rebuilt, but this fragment's items were not
1153     * included in the newly built menu (its {@link #onCreateOptionsMenu(Menu, MenuInflater)}
1154     * was not called).
1155     */
1156    public void onDestroyOptionsMenu() {
1157    }
1158
1159    /**
1160     * This hook is called whenever an item in your options menu is selected.
1161     * The default implementation simply returns false to have the normal
1162     * processing happen (calling the item's Runnable or sending a message to
1163     * its Handler as appropriate).  You can use this method for any items
1164     * for which you would like to do processing without those other
1165     * facilities.
1166     *
1167     * <p>Derived classes should call through to the base class for it to
1168     * perform the default menu handling.
1169     *
1170     * @param item The menu item that was selected.
1171     *
1172     * @return boolean Return false to allow normal menu processing to
1173     *         proceed, true to consume it here.
1174     *
1175     * @see #onCreateOptionsMenu
1176     */
1177    public boolean onOptionsItemSelected(MenuItem item) {
1178        return false;
1179    }
1180
1181    /**
1182     * This hook is called whenever the options menu is being closed (either by the user canceling
1183     * the menu with the back/menu button, or when an item is selected).
1184     *
1185     * @param menu The options menu as last shown or first initialized by
1186     *             onCreateOptionsMenu().
1187     */
1188    public void onOptionsMenuClosed(Menu menu) {
1189    }
1190
1191    /**
1192     * Called when a context menu for the {@code view} is about to be shown.
1193     * Unlike {@link #onCreateOptionsMenu}, this will be called every
1194     * time the context menu is about to be shown and should be populated for
1195     * the view (or item inside the view for {@link AdapterView} subclasses,
1196     * this can be found in the {@code menuInfo})).
1197     * <p>
1198     * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
1199     * item has been selected.
1200     * <p>
1201     * The default implementation calls up to
1202     * {@link Activity#onCreateContextMenu Activity.onCreateContextMenu}, though
1203     * you can not call this implementation if you don't want that behavior.
1204     * <p>
1205     * It is not safe to hold onto the context menu after this method returns.
1206     * {@inheritDoc}
1207     */
1208    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1209        getActivity().onCreateContextMenu(menu, v, menuInfo);
1210    }
1211
1212    /**
1213     * Registers a context menu to be shown for the given view (multiple views
1214     * can show the context menu). This method will set the
1215     * {@link OnCreateContextMenuListener} on the view to this fragment, so
1216     * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
1217     * called when it is time to show the context menu.
1218     *
1219     * @see #unregisterForContextMenu(View)
1220     * @param view The view that should show a context menu.
1221     */
1222    public void registerForContextMenu(View view) {
1223        view.setOnCreateContextMenuListener(this);
1224    }
1225
1226    /**
1227     * Prevents a context menu to be shown for the given view. This method will
1228     * remove the {@link OnCreateContextMenuListener} on the view.
1229     *
1230     * @see #registerForContextMenu(View)
1231     * @param view The view that should stop showing a context menu.
1232     */
1233    public void unregisterForContextMenu(View view) {
1234        view.setOnCreateContextMenuListener(null);
1235    }
1236
1237    /**
1238     * This hook is called whenever an item in a context menu is selected. The
1239     * default implementation simply returns false to have the normal processing
1240     * happen (calling the item's Runnable or sending a message to its Handler
1241     * as appropriate). You can use this method for any items for which you
1242     * would like to do processing without those other facilities.
1243     * <p>
1244     * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
1245     * View that added this menu item.
1246     * <p>
1247     * Derived classes should call through to the base class for it to perform
1248     * the default menu handling.
1249     *
1250     * @param item The context menu item that was selected.
1251     * @return boolean Return false to allow normal context menu processing to
1252     *         proceed, true to consume it here.
1253     */
1254    public boolean onContextItemSelected(MenuItem item) {
1255        return false;
1256    }
1257
1258    /**
1259     * Print the Fragments's state into the given stream.
1260     *
1261     * @param prefix Text to print at the front of each line.
1262     * @param fd The raw file descriptor that the dump is being sent to.
1263     * @param writer The PrintWriter to which you should dump your state.  This will be
1264     * closed for you after you return.
1265     * @param args additional arguments to the dump request.
1266     */
1267    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
1268        writer.print(prefix); writer.print("mFragmentId=#");
1269                writer.print(Integer.toHexString(mFragmentId));
1270                writer.print(" mContainerId#=");
1271                writer.print(Integer.toHexString(mContainerId));
1272                writer.print(" mTag="); writer.println(mTag);
1273        writer.print(prefix); writer.print("mState="); writer.print(mState);
1274                writer.print(" mIndex="); writer.print(mIndex);
1275                writer.print(" mWho="); writer.print(mWho);
1276                writer.print(" mBackStackNesting="); writer.println(mBackStackNesting);
1277        writer.print(prefix); writer.print("mAdded="); writer.print(mAdded);
1278                writer.print(" mRemoving="); writer.print(mRemoving);
1279                writer.print(" mResumed="); writer.print(mResumed);
1280                writer.print(" mFromLayout="); writer.print(mFromLayout);
1281                writer.print(" mInLayout="); writer.println(mInLayout);
1282        writer.print(prefix); writer.print("mHidden="); writer.print(mHidden);
1283                writer.print(" mRetainInstance="); writer.print(mRetainInstance);
1284                writer.print(" mRetaining="); writer.print(mRetaining);
1285                writer.print(" mHasMenu="); writer.println(mHasMenu);
1286        if (mFragmentManager != null) {
1287            writer.print(prefix); writer.print("mFragmentManager=");
1288                    writer.println(mFragmentManager);
1289        }
1290        if (mImmediateActivity != null) {
1291            writer.print(prefix); writer.print("mImmediateActivity=");
1292                    writer.println(mImmediateActivity);
1293        }
1294        if (mActivity != null) {
1295            writer.print(prefix); writer.print("mActivity=");
1296                    writer.println(mActivity);
1297        }
1298        if (mArguments != null) {
1299            writer.print(prefix); writer.print("mArguments="); writer.println(mArguments);
1300        }
1301        if (mSavedFragmentState != null) {
1302            writer.print(prefix); writer.print("mSavedFragmentState=");
1303                    writer.println(mSavedFragmentState);
1304        }
1305        if (mSavedViewState != null) {
1306            writer.print(prefix); writer.print("mSavedViewState=");
1307                    writer.println(mSavedViewState);
1308        }
1309        if (mTarget != null) {
1310            writer.print(prefix); writer.print("mTarget="); writer.print(mTarget);
1311                    writer.print(" mTargetRequestCode=");
1312                    writer.println(mTargetRequestCode);
1313        }
1314        if (mNextAnim != 0) {
1315            writer.print(prefix); writer.print("mNextAnim="); writer.println(mNextAnim);
1316        }
1317        if (mContainer != null) {
1318            writer.print(prefix); writer.print("mContainer="); writer.println(mContainer);
1319        }
1320        if (mView != null) {
1321            writer.print(prefix); writer.print("mView="); writer.println(mView);
1322        }
1323        if (mAnimatingAway != null) {
1324            writer.print(prefix); writer.print("mAnimatingAway="); writer.println(mAnimatingAway);
1325            writer.print(prefix); writer.print("mStateAfterAnimating=");
1326                    writer.println(mStateAfterAnimating);
1327        }
1328        if (mLoaderManager != null) {
1329            writer.print(prefix); writer.println("Loader Manager:");
1330            mLoaderManager.dump(prefix + "  ", fd, writer, args);
1331        }
1332    }
1333
1334    void performStop() {
1335        onStop();
1336
1337        if (mLoadersStarted) {
1338            mLoadersStarted = false;
1339            if (!mCheckedForLoaderManager) {
1340                mCheckedForLoaderManager = true;
1341                mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
1342            }
1343            if (mLoaderManager != null) {
1344                if (mActivity == null || !mActivity.mChangingConfigurations) {
1345                    mLoaderManager.doStop();
1346                } else {
1347                    mLoaderManager.doRetain();
1348                }
1349            }
1350        }
1351    }
1352}
1353