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