Fragment.java revision bdd19bc338286e1042f59808545665a061e73ffc
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        sb.append("Fragment{");
530        sb.append(Integer.toHexString(System.identityHashCode(this)));
531        if (mIndex >= 0) {
532            sb.append(" #");
533            sb.append(mIndex);
534        }
535        if (mFragmentId != 0) {
536            sb.append(" id=0x");
537            sb.append(Integer.toHexString(mFragmentId));
538        }
539        if (mTag != null) {
540            sb.append(" ");
541            sb.append(mTag);
542        }
543        sb.append('}');
544        return sb.toString();
545    }
546
547    /**
548     * Return the identifier this fragment is known by.  This is either
549     * the android:id value supplied in a layout or the container view ID
550     * supplied when adding the fragment.
551     */
552    final public int getId() {
553        return mFragmentId;
554    }
555
556    /**
557     * Get the tag name of the fragment, if specified.
558     */
559    final public String getTag() {
560        return mTag;
561    }
562
563    /**
564     * Supply the construction arguments for this fragment.  This can only
565     * be called before the fragment has been attached to its activity; that
566     * is, you should call it immediately after constructing the fragment.  The
567     * arguments supplied here will be retained across fragment destroy and
568     * creation.
569     */
570    public void setArguments(Bundle args) {
571        if (mIndex >= 0) {
572            throw new IllegalStateException("Fragment already active");
573        }
574        mArguments = args;
575    }
576
577    /**
578     * Return the arguments supplied when the fragment was instantiated,
579     * if any.
580     */
581    final public Bundle getArguments() {
582        return mArguments;
583    }
584
585    /**
586     * Optional target for this fragment.  This may be used, for example,
587     * if this fragment is being started by another, and when done wants to
588     * give a result back to the first.  The target set here is retained
589     * across instances via {@link FragmentManager#putFragment
590     * FragmentManager.putFragment()}.
591     *
592     * @param fragment The fragment that is the target of this one.
593     * @param requestCode Optional request code, for convenience if you
594     * are going to call back with {@link #onActivityResult(int, int, Intent)}.
595     */
596    public void setTargetFragment(Fragment fragment, int requestCode) {
597        mTarget = fragment;
598        mTargetRequestCode = requestCode;
599    }
600
601    /**
602     * Return the target fragment set by {@link #setTargetFragment}.
603     */
604    final public Fragment getTargetFragment() {
605        return mTarget;
606    }
607
608    /**
609     * Return the target request code set by {@link #setTargetFragment}.
610     */
611    final public int getTargetRequestCode() {
612        return mTargetRequestCode;
613    }
614
615    /**
616     * Return the Activity this fragment is currently associated with.
617     */
618    final public Activity getActivity() {
619        return mActivity;
620    }
621
622    /**
623     * Return <code>getActivity().getResources()</code>.
624     */
625    final public Resources getResources() {
626        return mActivity.getResources();
627    }
628
629    /**
630     * Return a localized, styled CharSequence from the application's package's
631     * default string table.
632     *
633     * @param resId Resource id for the CharSequence text
634     */
635    public final CharSequence getText(int resId) {
636        return getResources().getText(resId);
637    }
638
639    /**
640     * Return a localized string from the application's package's
641     * default string table.
642     *
643     * @param resId Resource id for the string
644     */
645    public final String getString(int resId) {
646        return getResources().getString(resId);
647    }
648
649    /**
650     * Return a localized formatted string from the application's package's
651     * default string table, substituting the format arguments as defined in
652     * {@link java.util.Formatter} and {@link java.lang.String#format}.
653     *
654     * @param resId Resource id for the format string
655     * @param formatArgs The format arguments that will be used for substitution.
656     */
657
658    public final String getString(int resId, Object... formatArgs) {
659        return getResources().getString(resId, formatArgs);
660    }
661
662    /**
663     * Return the FragmentManager for interacting with fragments associated
664     * with this fragment's activity.  Note that this will be non-null slightly
665     * before {@link #getActivity()}, during the time from when the fragment is
666     * placed in a {@link FragmentTransaction} until it is committed and
667     * attached to its activity.
668     */
669    final public FragmentManager getFragmentManager() {
670        return mFragmentManager;
671    }
672
673    /**
674     * Return true if the fragment is currently added to its activity.
675     */
676    final public boolean isAdded() {
677        return mActivity != null && mActivity.mFragments.mAdded.contains(this);
678    }
679
680    /**
681     * Return true if the layout is included as part of an activity view
682     * hierarchy via the &lt;fragment&gt; tag.  This will always be true when
683     * fragments are created through the &lt;fragment&gt; tag, <em>except</em>
684     * in the case where an old fragment is restored from a previous state and
685     * it does not appear in the layout of the current state.
686     */
687    final public boolean isInLayout() {
688        return mInLayout;
689    }
690
691    /**
692     * Return true if the fragment is in the resumed state.  This is true
693     * for the duration of {@link #onResume()} and {@link #onPause()} as well.
694     */
695    final public boolean isResumed() {
696        return mResumed;
697    }
698
699    /**
700     * Return true if the fragment is currently visible to the user.  This means
701     * it: (1) has been added, (2) has its view attached to the window, and
702     * (3) is not hidden.
703     */
704    final public boolean isVisible() {
705        return isAdded() && !isHidden() && mView != null
706                && mView.getWindowToken() != null && mView.getVisibility() == View.VISIBLE;
707    }
708
709    /**
710     * Return true if the fragment has been hidden.  By default fragments
711     * are shown.  You can find out about changes to this state with
712     * {@link #onHiddenChanged}.  Note that the hidden state is orthogonal
713     * to other states -- that is, to be visible to the user, a fragment
714     * must be both started and not hidden.
715     */
716    final public boolean isHidden() {
717        return mHidden;
718    }
719
720    /**
721     * Called when the hidden state (as returned by {@link #isHidden()} of
722     * the fragment has changed.  Fragments start out not hidden; this will
723     * be called whenever the fragment changes state from that.
724     * @param hidden True if the fragment is now hidden, false if it is not
725     * visible.
726     */
727    public void onHiddenChanged(boolean hidden) {
728    }
729
730    /**
731     * Control whether a fragment instance is retained across Activity
732     * re-creation (such as from a configuration change).  This can only
733     * be used with fragments not in the back stack.  If set, the fragment
734     * lifecycle will be slightly different when an activity is recreated:
735     * <ul>
736     * <li> {@link #onDestroy()} will not be called (but {@link #onDetach()} still
737     * will be, because the fragment is being detached from its current activity).
738     * <li> {@link #onCreate(Bundle)} will not be called since the fragment
739     * is not being re-created.
740     * <li> {@link #onAttach(Activity)} and {@link #onActivityCreated(Bundle)} <b>will</b>
741     * still be called.
742     * </ul>
743     */
744    public void setRetainInstance(boolean retain) {
745        mRetainInstance = retain;
746    }
747
748    final public boolean getRetainInstance() {
749        return mRetainInstance;
750    }
751
752    /**
753     * Report that this fragment would like to participate in populating
754     * the options menu by receiving a call to {@link #onCreateOptionsMenu}
755     * and related methods.
756     *
757     * @param hasMenu If true, the fragment has menu items to contribute.
758     */
759    public void setHasOptionsMenu(boolean hasMenu) {
760        if (mHasMenu != hasMenu) {
761            mHasMenu = hasMenu;
762            if (isAdded() && !isHidden()) {
763                mActivity.invalidateOptionsMenu();
764            }
765        }
766    }
767
768    /**
769     * Return the LoaderManager for this fragment, creating it if needed.
770     */
771    public LoaderManager getLoaderManager() {
772        if (mLoaderManager != null) {
773            return mLoaderManager;
774        }
775        mCheckedForLoaderManager = true;
776        mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, true);
777        return mLoaderManager;
778    }
779
780    /**
781     * Call {@link Activity#startActivity(Intent)} on the fragment's
782     * containing Activity.
783     */
784    public void startActivity(Intent intent) {
785        mActivity.startActivityFromFragment(this, intent, -1);
786    }
787
788    /**
789     * Call {@link Activity#startActivityForResult(Intent, int)} on the fragment's
790     * containing Activity.
791     */
792    public void startActivityForResult(Intent intent, int requestCode) {
793        mActivity.startActivityFromFragment(this, intent, requestCode);
794    }
795
796    /**
797     * Receive the result from a previous call to
798     * {@link #startActivityForResult(Intent, int)}.  This follows the
799     * related Activity API as described there in
800     * {@link Activity#onActivityResult(int, int, Intent)}.
801     *
802     * @param requestCode The integer request code originally supplied to
803     *                    startActivityForResult(), allowing you to identify who this
804     *                    result came from.
805     * @param resultCode The integer result code returned by the child activity
806     *                   through its setResult().
807     * @param data An Intent, which can return result data to the caller
808     *               (various data can be attached to Intent "extras").
809     */
810    public void onActivityResult(int requestCode, int resultCode, Intent data) {
811    }
812
813    /**
814     * Called when a fragment is being created as part of a view layout
815     * inflation, typically from setting the content view of an activity.  This
816     * will be called immediately after the fragment is created from a <fragment>
817     * tag in a layout file.  Note this is <em>before</em> the fragment's
818     * {@link #onAttach(Activity)} has been called; all you should do here is
819     * parse the attributes and save them away.  A convenient thing to do is
820     * simply copy them into a Bundle that is given to {@link #setArguments(Bundle)}.
821     *
822     * <p>This is called every time the fragment is inflated, even if it is
823     * being inflated into a new instance with saved state.  Because a fragment's
824     * arguments are retained across instances, it may make no sense to re-parse
825     * the attributes into new arguments.  You may want to first check
826     * {@link #getArguments()} and only parse the attributes if it returns null,
827     * the assumption being that if it is non-null those are the same arguments
828     * from the first time the fragment was inflated.  (That said, you may want
829     * to have layouts change for different configurations such as landscape
830     * and portrait, which can have different attributes.  If so, you will need
831     * to re-parse the attributes each time this is called to generate new
832     * arguments.)</p>
833     *
834     * @param attrs The attributes at the tag where the fragment is
835     * being created.
836     * @param savedInstanceState If the fragment is being re-created from
837     * a previous saved state, this is the state.
838     */
839    public void onInflate(AttributeSet attrs, Bundle savedInstanceState) {
840        mCalled = true;
841    }
842
843    /**
844     * Called when a fragment is first attached to its activity.
845     * {@link #onCreate(Bundle)} will be called after this.
846     */
847    public void onAttach(Activity activity) {
848        mCalled = true;
849    }
850
851    /**
852     * Called when a fragment loads an animation.
853     */
854    public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) {
855        return null;
856    }
857
858    /**
859     * Called to do initial creation of a fragment.  This is called after
860     * {@link #onAttach(Activity)} and before
861     * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
862     *
863     * <p>Note that this can be called while the fragment's activity is
864     * still in the process of being created.  As such, you can not rely
865     * on things like the activity's content view hierarchy being initialized
866     * at this point.  If you want to do work once the activity itself is
867     * created, see {@link #onActivityCreated(Bundle)}.
868     *
869     * @param savedInstanceState If the fragment is being re-created from
870     * a previous saved state, this is the state.
871     */
872    public void onCreate(Bundle savedInstanceState) {
873        mCalled = true;
874    }
875
876    /**
877     * Called to have the fragment instantiate its user interface view.
878     * This is optional, and non-graphical fragments can return null (which
879     * is the default implementation).  This will be called between
880     * {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}.
881     *
882     * <p>If you return a View from here, you will later be called in
883     * {@link #onDestroyView} when the view is being released.
884     *
885     * @param inflater The LayoutInflater object that can be used to inflate
886     * any views in the fragment,
887     * @param container If non-null, this is the parent view that the fragment's
888     * UI should be attached to.  The fragment should not add the view itself,
889     * but this can be used to generate the LayoutParams of the view.
890     * @param savedInstanceState If non-null, this fragment is being re-constructed
891     * from a previous saved state as given here.
892     *
893     * @return Return the View for the fragment's UI, or null.
894     */
895    public View onCreateView(LayoutInflater inflater, ViewGroup container,
896            Bundle savedInstanceState) {
897        return null;
898    }
899
900    public View getView() {
901        return mView;
902    }
903
904    /**
905     * Called when the fragment's activity has been created and this
906     * fragment's view hierarchy instantiated.  It can be used to do final
907     * initialization once these pieces are in place, such as retrieving
908     * views or restoring state.  It is also useful for fragments that use
909     * {@link #setRetainInstance(boolean)} to retain their instance,
910     * as this callback tells the fragment when it is fully associated with
911     * the new activity instance.  This is called after {@link #onCreateView}
912     * and before {@link #onStart()}.
913     *
914     * @param savedInstanceState If the fragment is being re-created from
915     * a previous saved state, this is the state.
916     */
917    public void onActivityCreated(Bundle savedInstanceState) {
918        mCalled = true;
919    }
920
921    /**
922     * Called when the Fragment is visible to the user.  This is generally
923     * tied to {@link Activity#onStart() Activity.onStart} of the containing
924     * Activity's lifecycle.
925     */
926    public void onStart() {
927        mCalled = true;
928
929        if (!mLoadersStarted) {
930            mLoadersStarted = true;
931            if (!mCheckedForLoaderManager) {
932                mCheckedForLoaderManager = true;
933                mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
934            }
935            if (mLoaderManager != null) {
936                mLoaderManager.doStart();
937            }
938        }
939    }
940
941    /**
942     * Called when the fragment is visible to the user and actively running.
943     * This is generally
944     * tied to {@link Activity#onResume() Activity.onResume} of the containing
945     * Activity's lifecycle.
946     */
947    public void onResume() {
948        mCalled = true;
949    }
950
951    /**
952     * Called to ask the fragment to save its current dynamic state, so it
953     * can later be reconstructed in a new instance of its process is
954     * restarted.  If a new instance of the fragment later needs to be
955     * created, the data you place in the Bundle here will be available
956     * in the Bundle given to {@link #onCreate(Bundle)},
957     * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}, and
958     * {@link #onActivityCreated(Bundle)}.
959     *
960     * <p>This corresponds to {@link Activity#onSaveInstanceState(Bundle)
961     * Activity.onSaveInstanceState(Bundle)} and most of the discussion there
962     * applies here as well.  Note however: <em>this method may be called
963     * at any time before {@link #onDestroy()}</em>.  There are many situations
964     * where a fragment may be mostly torn down (such as when placed on the
965     * back stack with no UI showing), but its state will not be saved until
966     * its owning activity actually needs to save its state.
967     *
968     * @param outState Bundle in which to place your saved state.
969     */
970    public void onSaveInstanceState(Bundle outState) {
971    }
972
973    public void onConfigurationChanged(Configuration newConfig) {
974        mCalled = true;
975    }
976
977    /**
978     * Called when the Fragment is no longer resumed.  This is generally
979     * tied to {@link Activity#onPause() Activity.onPause} of the containing
980     * Activity's lifecycle.
981     */
982    public void onPause() {
983        mCalled = true;
984    }
985
986    /**
987     * Called when the Fragment is no longer started.  This is generally
988     * tied to {@link Activity#onStop() Activity.onStop} of the containing
989     * Activity's lifecycle.
990     */
991    public void onStop() {
992        mCalled = true;
993    }
994
995    public void onLowMemory() {
996        mCalled = true;
997    }
998
999    /**
1000     * Called when the view previously created by {@link #onCreateView} has
1001     * been detached from the fragment.  The next time the fragment needs
1002     * to be displayed, a new view will be created.  This is called
1003     * after {@link #onStop()} and before {@link #onDestroy()}.  It is called
1004     * <em>regardless</em> of whether {@link #onCreateView} returned a
1005     * non-null view.  Internally it is called after the view's state has
1006     * been saved but before it has been removed from its parent.
1007     */
1008    public void onDestroyView() {
1009        mCalled = true;
1010    }
1011
1012    /**
1013     * Called when the fragment is no longer in use.  This is called
1014     * after {@link #onStop()} and before {@link #onDetach()}.
1015     */
1016    public void onDestroy() {
1017        mCalled = true;
1018        //Log.v("foo", "onDestroy: mCheckedForLoaderManager=" + mCheckedForLoaderManager
1019        //        + " mLoaderManager=" + mLoaderManager);
1020        if (!mCheckedForLoaderManager) {
1021            mCheckedForLoaderManager = true;
1022            mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
1023        }
1024        if (mLoaderManager != null) {
1025            mLoaderManager.doDestroy();
1026        }
1027    }
1028
1029    /**
1030     * Called when the fragment is no longer attached to its activity.  This
1031     * is called after {@link #onDestroy()}.
1032     */
1033    public void onDetach() {
1034        mCalled = true;
1035    }
1036
1037    /**
1038     * Initialize the contents of the Activity's standard options menu.  You
1039     * should place your menu items in to <var>menu</var>.  For this method
1040     * to be called, you must have first called {@link #setHasOptionsMenu}.  See
1041     * {@link Activity#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu}
1042     * for more information.
1043     *
1044     * @param menu The options menu in which you place your items.
1045     *
1046     * @see #setHasOptionsMenu
1047     * @see #onPrepareOptionsMenu
1048     * @see #onOptionsItemSelected
1049     */
1050    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
1051    }
1052
1053    /**
1054     * Prepare the Screen's standard options menu to be displayed.  This is
1055     * called right before the menu is shown, every time it is shown.  You can
1056     * use this method to efficiently enable/disable items or otherwise
1057     * dynamically modify the contents.  See
1058     * {@link Activity#onPrepareOptionsMenu(Menu) Activity.onPrepareOptionsMenu}
1059     * for more information.
1060     *
1061     * @param menu The options menu as last shown or first initialized by
1062     *             onCreateOptionsMenu().
1063     *
1064     * @see #setHasOptionsMenu
1065     * @see #onCreateOptionsMenu
1066     */
1067    public void onPrepareOptionsMenu(Menu menu) {
1068    }
1069
1070    /**
1071     * Called when this fragment's option menu items are no longer being
1072     * included in the overall options menu.  Receiving this call means that
1073     * the menu needed to be rebuilt, but this fragment's items were not
1074     * included in the newly built menu (its {@link #onCreateOptionsMenu(Menu, MenuInflater)}
1075     * was not called).
1076     */
1077    public void onDestroyOptionsMenu() {
1078    }
1079
1080    /**
1081     * This hook is called whenever an item in your options menu is selected.
1082     * The default implementation simply returns false to have the normal
1083     * processing happen (calling the item's Runnable or sending a message to
1084     * its Handler as appropriate).  You can use this method for any items
1085     * for which you would like to do processing without those other
1086     * facilities.
1087     *
1088     * <p>Derived classes should call through to the base class for it to
1089     * perform the default menu handling.
1090     *
1091     * @param item The menu item that was selected.
1092     *
1093     * @return boolean Return false to allow normal menu processing to
1094     *         proceed, true to consume it here.
1095     *
1096     * @see #onCreateOptionsMenu
1097     */
1098    public boolean onOptionsItemSelected(MenuItem item) {
1099        return false;
1100    }
1101
1102    /**
1103     * This hook is called whenever the options menu is being closed (either by the user canceling
1104     * the menu with the back/menu button, or when an item is selected).
1105     *
1106     * @param menu The options menu as last shown or first initialized by
1107     *             onCreateOptionsMenu().
1108     */
1109    public void onOptionsMenuClosed(Menu menu) {
1110    }
1111
1112    /**
1113     * Called when a context menu for the {@code view} is about to be shown.
1114     * Unlike {@link #onCreateOptionsMenu}, this will be called every
1115     * time the context menu is about to be shown and should be populated for
1116     * the view (or item inside the view for {@link AdapterView} subclasses,
1117     * this can be found in the {@code menuInfo})).
1118     * <p>
1119     * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
1120     * item has been selected.
1121     * <p>
1122     * The default implementation calls up to
1123     * {@link Activity#onCreateContextMenu Activity.onCreateContextMenu}, though
1124     * you can not call this implementation if you don't want that behavior.
1125     * <p>
1126     * It is not safe to hold onto the context menu after this method returns.
1127     * {@inheritDoc}
1128     */
1129    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1130        getActivity().onCreateContextMenu(menu, v, menuInfo);
1131    }
1132
1133    /**
1134     * Registers a context menu to be shown for the given view (multiple views
1135     * can show the context menu). This method will set the
1136     * {@link OnCreateContextMenuListener} on the view to this fragment, so
1137     * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
1138     * called when it is time to show the context menu.
1139     *
1140     * @see #unregisterForContextMenu(View)
1141     * @param view The view that should show a context menu.
1142     */
1143    public void registerForContextMenu(View view) {
1144        view.setOnCreateContextMenuListener(this);
1145    }
1146
1147    /**
1148     * Prevents a context menu to be shown for the given view. This method will
1149     * remove the {@link OnCreateContextMenuListener} on the view.
1150     *
1151     * @see #registerForContextMenu(View)
1152     * @param view The view that should stop showing a context menu.
1153     */
1154    public void unregisterForContextMenu(View view) {
1155        view.setOnCreateContextMenuListener(null);
1156    }
1157
1158    /**
1159     * This hook is called whenever an item in a context menu is selected. The
1160     * default implementation simply returns false to have the normal processing
1161     * happen (calling the item's Runnable or sending a message to its Handler
1162     * as appropriate). You can use this method for any items for which you
1163     * would like to do processing without those other facilities.
1164     * <p>
1165     * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
1166     * View that added this menu item.
1167     * <p>
1168     * Derived classes should call through to the base class for it to perform
1169     * the default menu handling.
1170     *
1171     * @param item The context menu item that was selected.
1172     * @return boolean Return false to allow normal context menu processing to
1173     *         proceed, true to consume it here.
1174     */
1175    public boolean onContextItemSelected(MenuItem item) {
1176        return false;
1177    }
1178
1179    /**
1180     * Print the Fragments's state into the given stream.
1181     *
1182     * @param prefix Text to print at the front of each line.
1183     * @param fd The raw file descriptor that the dump is being sent to.
1184     * @param writer The PrintWriter to which you should dump your state.  This will be
1185     * closed for you after you return.
1186     * @param args additional arguments to the dump request.
1187     */
1188    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
1189        writer.print(prefix); writer.print("mFragmentId="); writer.print(mFragmentId);
1190                writer.print(" mContainerId="); writer.print(mContainerId);
1191                writer.print(" mTag="); writer.println(mTag);
1192        writer.print(prefix); writer.print("mState="); writer.print(mState);
1193                writer.print(" mIndex="); writer.print(mIndex);
1194                writer.print(" mWho="); writer.print(mWho);
1195                writer.print(" mBackStackNesting="); writer.println(mBackStackNesting);
1196        writer.print(prefix); writer.print("mAdded="); writer.print(mAdded);
1197                writer.print(" mResumed="); writer.print(mResumed);
1198                writer.print(" mFromLayout="); writer.print(mFromLayout);
1199                writer.print(" mInLayout="); writer.println(mInLayout);
1200        writer.print(prefix); writer.print("mHidden="); writer.print(mHidden);
1201                writer.print(" mRetainInstance="); writer.print(mRetainInstance);
1202                writer.print(" mRetaining="); writer.print(mRetaining);
1203                writer.print(" mHasMenu="); writer.println(mHasMenu);
1204        if (mFragmentManager != null) {
1205            writer.print(prefix); writer.print("mFragmentManager=");
1206                    writer.println(mFragmentManager);
1207        }
1208        if (mImmediateActivity != null) {
1209            writer.print(prefix); writer.print("mImmediateActivity=");
1210                    writer.println(mImmediateActivity);
1211        }
1212        if (mActivity != null) {
1213            writer.print(prefix); writer.print("mActivity=");
1214                    writer.println(mActivity);
1215        }
1216        if (mArguments != null) {
1217            writer.print(prefix); writer.print("mArguments="); writer.println(mArguments);
1218        }
1219        if (mSavedFragmentState != null) {
1220            writer.print(prefix); writer.print("mSavedFragmentState=");
1221                    writer.println(mSavedFragmentState);
1222        }
1223        if (mSavedViewState != null) {
1224            writer.print(prefix); writer.print("mSavedViewState=");
1225                    writer.println(mSavedViewState);
1226        }
1227        if (mTarget != null) {
1228            writer.print(prefix); writer.print("mTarget="); writer.print(mTarget);
1229                    writer.print(" mTargetRequestCode=");
1230                    writer.println(mTargetRequestCode);
1231        }
1232        if (mNextAnim != 0) {
1233            writer.print(prefix); writer.print("mNextAnim="); writer.println(mNextAnim);
1234        }
1235        if (mContainer != null) {
1236            writer.print(prefix); writer.print("mContainer="); writer.println(mContainer);
1237        }
1238        if (mView != null) {
1239            writer.print(prefix); writer.print("mView="); writer.println(mView);
1240        }
1241        if (mLoaderManager != null) {
1242            writer.print(prefix); writer.print("mLoaderManager="); writer.print(mLoaderManager);
1243                    writer.print(" mLoadersStarted="); writer.print(mLoadersStarted);
1244                    writer.print(" mCheckedForLoaderManager=");
1245                    writer.println(mCheckedForLoaderManager);
1246        }
1247    }
1248
1249    void performStop() {
1250        onStop();
1251
1252        if (mLoadersStarted) {
1253            mLoadersStarted = false;
1254            if (!mCheckedForLoaderManager) {
1255                mCheckedForLoaderManager = true;
1256                mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
1257            }
1258            if (mLoaderManager != null) {
1259                if (mActivity == null || !mActivity.mChangingConfigurations) {
1260                    mLoaderManager.doStop();
1261                } else {
1262                    mLoaderManager.doRetain();
1263                }
1264            }
1265        }
1266    }
1267}
1268