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