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