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