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