2 * Copyright (C) 2011 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package android.support.v2.app;
19 import android.app.Activity;
20 import android.content.ComponentCallbacks;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.content.res.Configuration;
24 import android.content.res.Resources;
25 import android.os.Bundle;
26 import android.os.Parcel;
27 import android.os.Parcelable;
28 import android.support.v2.util.DebugUtils;
29 import android.util.AttributeSet;
30 import android.util.SparseArray;
31 import android.view.ContextMenu;
32 import android.view.LayoutInflater;
33 import android.view.Menu;
34 import android.view.MenuInflater;
35 import android.view.MenuItem;
36 import android.view.View;
37 import android.view.ViewGroup;
38 import android.view.ContextMenu.ContextMenuInfo;
39 import android.view.View.OnCreateContextMenuListener;
40 import android.view.animation.Animation;
41 import android.widget.AdapterView;
43 import java.io.FileDescriptor;
44 import java.io.PrintWriter;
45 import java.util.HashMap;
47 final class FragmentState implements Parcelable {
48 final String mClassName;
50 final boolean mFromLayout;
51 final int mFragmentId;
52 final int mContainerId;
54 final boolean mRetainInstance;
55 final Bundle mArguments;
57 Bundle mSavedFragmentState;
61 public FragmentState(Fragment frag) {
62 mClassName = frag.getClass().getName();
64 mFromLayout = frag.mFromLayout;
65 mFragmentId = frag.mFragmentId;
66 mContainerId = frag.mContainerId;
68 mRetainInstance = frag.mRetainInstance;
69 mArguments = frag.mArguments;
72 public FragmentState(Parcel in) {
73 mClassName = in.readString();
74 mIndex = in.readInt();
75 mFromLayout = in.readInt() != 0;
76 mFragmentId = in.readInt();
77 mContainerId = in.readInt();
78 mTag = in.readString();
79 mRetainInstance = in.readInt() != 0;
80 mArguments = in.readBundle();
81 mSavedFragmentState = in.readBundle();
84 public Fragment instantiate(FragmentActivity activity) {
85 if (mInstance != null) {
89 if (mArguments != null) {
90 mArguments.setClassLoader(activity.getClassLoader());
93 mInstance = Fragment.instantiate(activity, mClassName, mArguments);
95 if (mSavedFragmentState != null) {
96 mSavedFragmentState.setClassLoader(activity.getClassLoader());
97 mInstance.mSavedFragmentState = mSavedFragmentState;
99 mInstance.setIndex(mIndex);
100 mInstance.mFromLayout = mFromLayout;
101 mInstance.mRestored = true;
102 mInstance.mFragmentId = mFragmentId;
103 mInstance.mContainerId = mContainerId;
104 mInstance.mTag = mTag;
105 mInstance.mRetainInstance = mRetainInstance;
106 mInstance.mFragmentManager = activity.mFragments;
111 public int describeContents() {
115 public void writeToParcel(Parcel dest, int flags) {
116 dest.writeString(mClassName);
117 dest.writeInt(mIndex);
118 dest.writeInt(mFromLayout ? 1 : 0);
119 dest.writeInt(mFragmentId);
120 dest.writeInt(mContainerId);
121 dest.writeString(mTag);
122 dest.writeInt(mRetainInstance ? 1 : 0);
123 dest.writeBundle(mArguments);
124 dest.writeBundle(mSavedFragmentState);
127 public static final Parcelable.Creator<FragmentState> CREATOR
128 = new Parcelable.Creator<FragmentState>() {
129 public FragmentState createFromParcel(Parcel in) {
130 return new FragmentState(in);
133 public FragmentState[] newArray(int size) {
134 return new FragmentState[size];
140 * Static library support version of the framework's {@link android.app.Fragment}.
141 * Used to write apps that run on platforms prior to Android 3.0. When running
142 * on Android 3.0 or above, this implementation is still used; it does not try
143 * to switch to the framework's implementation. See the framework SDK
144 * documentation for a class overview.
146 public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener {
147 private static final HashMap<String, Class<?>> sClassMap =
148 new HashMap<String, Class<?>>();
150 static final int INITIALIZING = 0; // Not yet created.
151 static final int CREATED = 1; // Created.
152 static final int ACTIVITY_CREATED = 2; // The activity has finished its creation.
153 static final int STARTED = 3; // Created and started, not resumed.
154 static final int RESUMED = 4; // Created started and resumed.
156 int mState = INITIALIZING;
158 // Non-null if the fragment's view hierarchy is currently animating away,
159 // meaning we need to wait a bit on completely destroying it. This is the
160 // view that is animating.
163 // If mAnimatingAway != null, this is the state we should move to once the
164 // animation is done.
165 int mStateAfterAnimating;
167 // When instantiated from saved state, this is the saved state.
168 Bundle mSavedFragmentState;
169 SparseArray<Parcelable> mSavedViewState;
171 // Index into active fragment array.
174 // Internal unique name for this fragment;
177 // Construction arguments;
183 // Target request code.
184 int mTargetRequestCode;
186 // True if the fragment is in the list of added fragments.
189 // If set this fragment is being removed from its activity.
192 // True if the fragment is in the resumed state.
195 // Set to true if this fragment was instantiated from a layout file.
198 // Set to true when the view has actually been inflated in its layout.
201 // True if this fragment has been restored from previously saved state.
204 // Number of active back stack entries this fragment is in.
205 int mBackStackNesting;
207 // The fragment manager we are associated with. Set as soon as the
208 // fragment is used in a transaction; cleared after it has been removed
209 // from all transactions.
210 FragmentManager mFragmentManager;
212 // Set as soon as a fragment is added to a transaction (or removed),
213 // to be able to do validation.
214 FragmentActivity mImmediateActivity;
216 // Activity this fragment is attached to.
217 FragmentActivity mActivity;
219 // The optional identifier for this fragment -- either the container ID if it
220 // was dynamically added to the view hierarchy, or the ID supplied in
224 // When a fragment is being dynamically added to the view hierarchy, this
225 // is the identifier of the parent container it is being added to.
228 // The optional named tag for this fragment -- usually used to find
229 // fragments that are not part of the layout.
232 // Set to true when the app has requested that this fragment be hidden
236 // If set this fragment would like its instance retained across
237 // configuration changes.
238 boolean mRetainInstance;
240 // If set this fragment is being retained across the current config change.
243 // If set this fragment has menu items to contribute.
246 // Used to verify that subclasses call through to super class.
249 // If app has requested a specific animation, this is the one to use.
252 // The parent container of the fragment after dynamically added to UI.
253 ViewGroup mContainer;
255 // The View generated for this fragment.
258 // The real inner view that will save/restore state.
261 LoaderManagerImpl mLoaderManager;
262 boolean mLoadersStarted;
263 boolean mCheckedForLoaderManager;
266 * Thrown by {@link Fragment#instantiate(Context, String, Bundle)} when
267 * there is an instantiation failure.
269 static public class InstantiationException extends RuntimeException {
270 public InstantiationException(String msg, Exception cause) {
276 * Default constructor. <strong>Every</strong> fragment must have an
277 * empty constructor, so it can be instantiated when restoring its
278 * activity's state. It is strongly recommended that subclasses do not
279 * have other constructors with parameters, since these constructors
280 * will not be called when the fragment is re-instantiated; instead,
281 * arguments can be supplied by the caller with {@link #setArguments}
282 * and later retrieved by the Fragment with {@link #getArguments}.
284 * <p>Applications should generally not implement a constructor. The
285 * first place application code an run where the fragment is ready to
286 * be used is in {@link #onAttach(Activity)}, the point where the fragment
287 * is actually associated with its activity. Some applications may also
288 * want to implement {@link #onInflate} to retrieve attributes from a
289 * layout resource, though should take care here because this happens for
290 * the fragment is attached to its activity.
296 * Like {@link #instantiate(Context, String, Bundle)} but with a null
299 public static Fragment instantiate(Context context, String fname) {
300 return instantiate(context, fname, null);
304 * Create a new instance of a Fragment with the given class name. This is
305 * the same as calling its empty constructor.
307 * @param context The calling context being used to instantiate the fragment.
308 * This is currently just used to get its ClassLoader.
309 * @param fname The class name of the fragment to instantiate.
310 * @param args Bundle of arguments to supply to the fragment, which it
311 * can retrieve with {@link #getArguments()}. May be null.
312 * @return Returns a new fragment instance.
313 * @throws InstantiationException If there is a failure in instantiating
314 * the given fragment class. This is a runtime exception; it is not
315 * normally expected to happen.
317 public static Fragment instantiate(Context context, String fname, Bundle args) {
319 Class<?> clazz = sClassMap.get(fname);
321 // Class not found in the cache, see if it's real, and try to add it
322 clazz = context.getClassLoader().loadClass(fname);
323 sClassMap.put(fname, clazz);
325 Fragment f = (Fragment)clazz.newInstance();
327 args.setClassLoader(f.getClass().getClassLoader());
331 } catch (ClassNotFoundException e) {
332 throw new InstantiationException("Unable to instantiate fragment " + fname
333 + ": make sure class name exists, is public, and has an"
334 + " empty constructor that is public", e);
335 } catch (java.lang.InstantiationException e) {
336 throw new InstantiationException("Unable to instantiate fragment " + fname
337 + ": make sure class name exists, is public, and has an"
338 + " empty constructor that is public", e);
339 } catch (IllegalAccessException 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);
346 void restoreViewState() {
347 if (mSavedViewState != null) {
348 mInnerView.restoreHierarchyState(mSavedViewState);
349 mSavedViewState = null;
353 void setIndex(int index) {
355 mWho = "android:fragment:" + mIndex;
364 * Subclasses can not override equals().
366 @Override final public boolean equals(Object o) {
367 return super.equals(o);
371 * Subclasses can not override hashCode().
373 @Override final public int hashCode() {
374 return super.hashCode();
378 public String toString() {
379 StringBuilder sb = new StringBuilder(128);
380 DebugUtils.buildShortClassTag(this, sb);
385 if (mFragmentId != 0) {
387 sb.append(Integer.toHexString(mFragmentId));
394 return sb.toString();
398 * Return the identifier this fragment is known by. This is either
399 * the android:id value supplied in a layout or the container view ID
400 * supplied when adding the fragment.
402 final public int getId() {
407 * Get the tag name of the fragment, if specified.
409 final public String getTag() {
414 * Supply the construction arguments for this fragment. This can only
415 * be called before the fragment has been attached to its activity; that
416 * is, you should call it immediately after constructing the fragment. The
417 * arguments supplied here will be retained across fragment destroy and
420 public void setArguments(Bundle args) {
422 throw new IllegalStateException("Fragment already active");
428 * Return the arguments supplied when the fragment was instantiated,
431 final public Bundle getArguments() {
436 * Optional target for this fragment. This may be used, for example,
437 * if this fragment is being started by another, and when done wants to
438 * give a result back to the first. The target set here is retained
439 * across instances via {@link FragmentManager#putFragment
440 * FragmentManager.putFragment()}.
442 * @param fragment The fragment that is the target of this one.
443 * @param requestCode Optional request code, for convenience if you
444 * are going to call back with {@link #onActivityResult(int, int, Intent)}.
446 public void setTargetFragment(Fragment fragment, int requestCode) {
448 mTargetRequestCode = requestCode;
452 * Return the target fragment set by {@link #setTargetFragment}.
454 final public Fragment getTargetFragment() {
459 * Return the target request code set by {@link #setTargetFragment}.
461 final public int getTargetRequestCode() {
462 return mTargetRequestCode;
466 * Return the Activity this fragment is currently associated with.
468 final public FragmentActivity getActivity() {
473 * Return <code>getActivity().getResources()</code>.
475 final public Resources getResources() {
476 if (mActivity == null) {
477 throw new IllegalStateException("Fragment " + this + " not attached to Activity");
479 return mActivity.getResources();
483 * Return a localized, styled CharSequence from the application's package's
484 * default string table.
486 * @param resId Resource id for the CharSequence text
488 public final CharSequence getText(int resId) {
489 return getResources().getText(resId);
493 * Return a localized string from the application's package's
494 * default string table.
496 * @param resId Resource id for the string
498 public final String getString(int resId) {
499 return getResources().getString(resId);
503 * Return a localized formatted string from the application's package's
504 * default string table, substituting the format arguments as defined in
505 * {@link java.util.Formatter} and {@link java.lang.String#format}.
507 * @param resId Resource id for the format string
508 * @param formatArgs The format arguments that will be used for substitution.
511 public final String getString(int resId, Object... formatArgs) {
512 return getResources().getString(resId, formatArgs);
516 * Return the FragmentManager for interacting with fragments associated
517 * with this fragment's activity. Note that this will be non-null slightly
518 * before {@link #getActivity()}, during the time from when the fragment is
519 * placed in a {@link FragmentTransaction} until it is committed and
520 * attached to its activity.
522 final public FragmentManager getFragmentManager() {
523 return mFragmentManager;
527 * Return true if the fragment is currently added to its activity.
529 final public boolean isAdded() {
530 return mActivity != null && mAdded;
534 * Return true if this fragment is currently being removed from its
535 * activity. This is <em>not</em> whether its activity is finishing, but
536 * rather whether it is in the process of being removed from its activity.
538 final public boolean isRemoving() {
543 * Return true if the layout is included as part of an activity view
544 * hierarchy via the <fragment> tag. This will always be true when
545 * fragments are created through the <fragment> tag, <em>except</em>
546 * in the case where an old fragment is restored from a previous state and
547 * it does not appear in the layout of the current state.
549 final public boolean isInLayout() {
554 * Return true if the fragment is in the resumed state. This is true
555 * for the duration of {@link #onResume()} and {@link #onPause()} as well.
557 final public boolean isResumed() {
562 * Return true if the fragment is currently visible to the user. This means
563 * it: (1) has been added, (2) has its view attached to the window, and
566 final public boolean isVisible() {
567 return isAdded() && !isHidden() && mView != null
568 && mView.getWindowToken() != null && mView.getVisibility() == View.VISIBLE;
572 * Return true if the fragment has been hidden. By default fragments
573 * are shown. You can find out about changes to this state with
574 * {@link #onHiddenChanged}. Note that the hidden state is orthogonal
575 * to other states -- that is, to be visible to the user, a fragment
576 * must be both started and not hidden.
578 final public boolean isHidden() {
583 * Called when the hidden state (as returned by {@link #isHidden()} of
584 * the fragment has changed. Fragments start out not hidden; this will
585 * be called whenever the fragment changes state from that.
586 * @param hidden True if the fragment is now hidden, false if it is not
589 public void onHiddenChanged(boolean hidden) {
593 * Control whether a fragment instance is retained across Activity
594 * re-creation (such as from a configuration change). This can only
595 * be used with fragments not in the back stack. If set, the fragment
596 * lifecycle will be slightly different when an activity is recreated:
598 * <li> {@link #onDestroy()} will not be called (but {@link #onDetach()} still
599 * will be, because the fragment is being detached from its current activity).
600 * <li> {@link #onCreate(Bundle)} will not be called since the fragment
601 * is not being re-created.
602 * <li> {@link #onAttach(Activity)} and {@link #onActivityCreated(Bundle)} <b>will</b>
606 public void setRetainInstance(boolean retain) {
607 mRetainInstance = retain;
610 final public boolean getRetainInstance() {
611 return mRetainInstance;
615 * Report that this fragment would like to participate in populating
616 * the options menu by receiving a call to {@link #onCreateOptionsMenu}
617 * and related methods.
619 * @param hasMenu If true, the fragment has menu items to contribute.
621 public void setHasOptionsMenu(boolean hasMenu) {
622 if (mHasMenu != hasMenu) {
624 if (isAdded() && !isHidden()) {
625 mActivity.supportInvalidateOptionsMenu();
631 * Return the LoaderManager for this fragment, creating it if needed.
633 public LoaderManager getLoaderManager() {
634 if (mLoaderManager != null) {
635 return mLoaderManager;
637 if (mActivity == null) {
638 throw new IllegalStateException("Fragment " + this + " not attached to Activity");
640 mCheckedForLoaderManager = true;
641 mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, true);
642 return mLoaderManager;
646 * Call {@link Activity#startActivity(Intent)} on the fragment's
647 * containing Activity.
649 public void startActivity(Intent intent) {
650 if (mActivity == null) {
651 throw new IllegalStateException("Fragment " + this + " not attached to Activity");
653 mActivity.startActivityFromFragment(this, intent, -1);
657 * Call {@link Activity#startActivityForResult(Intent, int)} on the fragment's
658 * containing Activity.
660 public void startActivityForResult(Intent intent, int requestCode) {
661 if (mActivity == null) {
662 throw new IllegalStateException("Fragment " + this + " not attached to Activity");
664 mActivity.startActivityFromFragment(this, intent, requestCode);
668 * Receive the result from a previous call to
669 * {@link #startActivityForResult(Intent, int)}. This follows the
670 * related Activity API as described there in
671 * {@link Activity#onActivityResult(int, int, Intent)}.
673 * @param requestCode The integer request code originally supplied to
674 * startActivityForResult(), allowing you to identify who this
676 * @param resultCode The integer result code returned by the child activity
677 * through its setResult().
678 * @param data An Intent, which can return result data to the caller
679 * (various data can be attached to Intent "extras").
681 public void onActivityResult(int requestCode, int resultCode, Intent data) {
685 * @hide Hack so that DialogFragment can make its Dialog before creating
686 * its views, and the view construction can use the dialog's context for
687 * inflation. Maybe this should become a public API. Note sure.
689 public LayoutInflater getLayoutInflater(Bundle savedInstanceState) {
690 return mActivity.getLayoutInflater();
694 * Called when a fragment is being created as part of a view layout
695 * inflation, typically from setting the content view of an activity. This
696 * may be called immediately after the fragment is created from a <fragment>
697 * tag in a layout file. Note this is <em>before</em> the fragment's
698 * {@link #onAttach(Activity)} has been called; all you should do here is
699 * parse the attributes and save them away.
701 * <p>This is called every time the fragment is inflated, even if it is
702 * being inflated into a new instance with saved state. It typically makes
703 * sense to re-parse the parameters each time, to allow them to change with
704 * different configurations.</p>
706 * <p>Here is a typical implementation of a fragment that can take parameters
707 * both through attributes supplied here as well from {@link #getArguments()}:</p>
709 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
712 * <p>Note that parsing the XML attributes uses a "styleable" resource. The
713 * declaration for the styleable used here is:</p>
715 * {@sample development/samples/ApiDemos/res/values/attrs.xml fragment_arguments}
717 * <p>The fragment can then be declared within its activity's content layout
718 * through a tag like this:</p>
720 * {@sample development/samples/ApiDemos/res/layout/fragment_arguments.xml from_attributes}
722 * <p>This fragment can also be created dynamically from arguments given
723 * at runtime in the arguments Bundle; here is an example of doing so at
724 * creation of the containing activity:</p>
726 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
729 * @param activity The Activity that is inflating this fragment.
730 * @param attrs The attributes at the tag where the fragment is
732 * @param savedInstanceState If the fragment is being re-created from
733 * a previous saved state, this is the state.
735 public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
740 * Called when a fragment is first attached to its activity.
741 * {@link #onCreate(Bundle)} will be called after this.
743 public void onAttach(Activity activity) {
748 * Called when a fragment loads an animation.
750 public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
755 * Called to do initial creation of a fragment. This is called after
756 * {@link #onAttach(Activity)} and before
757 * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
759 * <p>Note that this can be called while the fragment's activity is
760 * still in the process of being created. As such, you can not rely
761 * on things like the activity's content view hierarchy being initialized
762 * at this point. If you want to do work once the activity itself is
763 * created, see {@link #onActivityCreated(Bundle)}.
765 * @param savedInstanceState If the fragment is being re-created from
766 * a previous saved state, this is the state.
768 public void onCreate(Bundle savedInstanceState) {
773 * Called to have the fragment instantiate its user interface view.
774 * This is optional, and non-graphical fragments can return null (which
775 * is the default implementation). This will be called between
776 * {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}.
778 * <p>If you return a View from here, you will later be called in
779 * {@link #onDestroyView} when the view is being released.
781 * @param inflater The LayoutInflater object that can be used to inflate
782 * any views in the fragment,
783 * @param container If non-null, this is the parent view that the fragment's
784 * UI should be attached to. The fragment should not add the view itself,
785 * but this can be used to generate the LayoutParams of the view.
786 * @param savedInstanceState If non-null, this fragment is being re-constructed
787 * from a previous saved state as given here.
789 * @return Return the View for the fragment's UI, or null.
791 public View onCreateView(LayoutInflater inflater, ViewGroup container,
792 Bundle savedInstanceState) {
797 * Get the root view for the fragment's layout (the one returned by {@link #onCreateView}),
800 * @return The fragment's root view, or null if it has no layout.
802 public View getView() {
807 * Called when the fragment's activity has been created and this
808 * fragment's view hierarchy instantiated. It can be used to do final
809 * initialization once these pieces are in place, such as retrieving
810 * views or restoring state. It is also useful for fragments that use
811 * {@link #setRetainInstance(boolean)} to retain their instance,
812 * as this callback tells the fragment when it is fully associated with
813 * the new activity instance. This is called after {@link #onCreateView}
814 * and before {@link #onStart()}.
816 * @param savedInstanceState If the fragment is being re-created from
817 * a previous saved state, this is the state.
819 public void onActivityCreated(Bundle savedInstanceState) {
824 * Called when the Fragment is visible to the user. This is generally
825 * tied to {@link Activity#onStart() Activity.onStart} of the containing
826 * Activity's lifecycle.
828 public void onStart() {
831 if (!mLoadersStarted) {
832 mLoadersStarted = true;
833 if (!mCheckedForLoaderManager) {
834 mCheckedForLoaderManager = true;
835 mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
837 if (mLoaderManager != null) {
838 mLoaderManager.doStart();
844 * Called when the fragment is visible to the user and actively running.
846 * tied to {@link Activity#onResume() Activity.onResume} of the containing
847 * Activity's lifecycle.
849 public void onResume() {
854 * Called to ask the fragment to save its current dynamic state, so it
855 * can later be reconstructed in a new instance of its process is
856 * restarted. If a new instance of the fragment later needs to be
857 * created, the data you place in the Bundle here will be available
858 * in the Bundle given to {@link #onCreate(Bundle)},
859 * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}, and
860 * {@link #onActivityCreated(Bundle)}.
862 * <p>This corresponds to {@link Activity#onSaveInstanceState(Bundle)
863 * Activity.onSaveInstanceState(Bundle)} and most of the discussion there
864 * applies here as well. Note however: <em>this method may be called
865 * at any time before {@link #onDestroy()}</em>. There are many situations
866 * where a fragment may be mostly torn down (such as when placed on the
867 * back stack with no UI showing), but its state will not be saved until
868 * its owning activity actually needs to save its state.
870 * @param outState Bundle in which to place your saved state.
872 public void onSaveInstanceState(Bundle outState) {
875 public void onConfigurationChanged(Configuration newConfig) {
880 * Called when the Fragment is no longer resumed. This is generally
881 * tied to {@link Activity#onPause() Activity.onPause} of the containing
882 * Activity's lifecycle.
884 public void onPause() {
889 * Called when the Fragment is no longer started. This is generally
890 * tied to {@link Activity#onStop() Activity.onStop} of the containing
891 * Activity's lifecycle.
893 public void onStop() {
897 public void onLowMemory() {
902 * Called when the view previously created by {@link #onCreateView} has
903 * been detached from the fragment. The next time the fragment needs
904 * to be displayed, a new view will be created. This is called
905 * after {@link #onStop()} and before {@link #onDestroy()}. It is called
906 * <em>regardless</em> of whether {@link #onCreateView} returned a
907 * non-null view. Internally it is called after the view's state has
908 * been saved but before it has been removed from its parent.
910 public void onDestroyView() {
915 * Called when the fragment is no longer in use. This is called
916 * after {@link #onStop()} and before {@link #onDetach()}.
918 public void onDestroy() {
920 //Log.v("foo", "onDestroy: mCheckedForLoaderManager=" + mCheckedForLoaderManager
921 // + " mLoaderManager=" + mLoaderManager);
922 if (!mCheckedForLoaderManager) {
923 mCheckedForLoaderManager = true;
924 mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
926 if (mLoaderManager != null) {
927 mLoaderManager.doDestroy();
932 * Called when the fragment is no longer attached to its activity. This
933 * is called after {@link #onDestroy()}.
935 public void onDetach() {
940 * Initialize the contents of the Activity's standard options menu. You
941 * should place your menu items in to <var>menu</var>. For this method
942 * to be called, you must have first called {@link #setHasOptionsMenu}. See
943 * {@link Activity#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu}
944 * for more information.
946 * @param menu The options menu in which you place your items.
948 * @see #setHasOptionsMenu
949 * @see #onPrepareOptionsMenu
950 * @see #onOptionsItemSelected
952 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
956 * Prepare the Screen's standard options menu to be displayed. This is
957 * called right before the menu is shown, every time it is shown. You can
958 * use this method to efficiently enable/disable items or otherwise
959 * dynamically modify the contents. See
960 * {@link Activity#onPrepareOptionsMenu(Menu) Activity.onPrepareOptionsMenu}
961 * for more information.
963 * @param menu The options menu as last shown or first initialized by
964 * onCreateOptionsMenu().
966 * @see #setHasOptionsMenu
967 * @see #onCreateOptionsMenu
969 public void onPrepareOptionsMenu(Menu menu) {
973 * Called when this fragment's option menu items are no longer being
974 * included in the overall options menu. Receiving this call means that
975 * the menu needed to be rebuilt, but this fragment's items were not
976 * included in the newly built menu (its {@link #onCreateOptionsMenu(Menu, MenuInflater)}
979 public void onDestroyOptionsMenu() {
983 * This hook is called whenever an item in your options menu is selected.
984 * The default implementation simply returns false to have the normal
985 * processing happen (calling the item's Runnable or sending a message to
986 * its Handler as appropriate). You can use this method for any items
987 * for which you would like to do processing without those other
990 * <p>Derived classes should call through to the base class for it to
991 * perform the default menu handling.
993 * @param item The menu item that was selected.
995 * @return boolean Return false to allow normal menu processing to
996 * proceed, true to consume it here.
998 * @see #onCreateOptionsMenu
1000 public boolean onOptionsItemSelected(MenuItem item) {
1005 * This hook is called whenever the options menu is being closed (either by the user canceling
1006 * the menu with the back/menu button, or when an item is selected).
1008 * @param menu The options menu as last shown or first initialized by
1009 * onCreateOptionsMenu().
1011 public void onOptionsMenuClosed(Menu menu) {
1015 * Called when a context menu for the {@code view} is about to be shown.
1016 * Unlike {@link #onCreateOptionsMenu}, this will be called every
1017 * time the context menu is about to be shown and should be populated for
1018 * the view (or item inside the view for {@link AdapterView} subclasses,
1019 * this can be found in the {@code menuInfo})).
1021 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
1022 * item has been selected.
1024 * The default implementation calls up to
1025 * {@link Activity#onCreateContextMenu Activity.onCreateContextMenu}, though
1026 * you can not call this implementation if you don't want that behavior.
1028 * It is not safe to hold onto the context menu after this method returns.
1031 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1032 getActivity().onCreateContextMenu(menu, v, menuInfo);
1036 * Registers a context menu to be shown for the given view (multiple views
1037 * can show the context menu). This method will set the
1038 * {@link OnCreateContextMenuListener} on the view to this fragment, so
1039 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
1040 * called when it is time to show the context menu.
1042 * @see #unregisterForContextMenu(View)
1043 * @param view The view that should show a context menu.
1045 public void registerForContextMenu(View view) {
1046 view.setOnCreateContextMenuListener(this);
1050 * Prevents a context menu to be shown for the given view. This method will
1051 * remove the {@link OnCreateContextMenuListener} on the view.
1053 * @see #registerForContextMenu(View)
1054 * @param view The view that should stop showing a context menu.
1056 public void unregisterForContextMenu(View view) {
1057 view.setOnCreateContextMenuListener(null);
1061 * This hook is called whenever an item in a context menu is selected. The
1062 * default implementation simply returns false to have the normal processing
1063 * happen (calling the item's Runnable or sending a message to its Handler
1064 * as appropriate). You can use this method for any items for which you
1065 * would like to do processing without those other facilities.
1067 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
1068 * View that added this menu item.
1070 * Derived classes should call through to the base class for it to perform
1071 * the default menu handling.
1073 * @param item The context menu item that was selected.
1074 * @return boolean Return false to allow normal context menu processing to
1075 * proceed, true to consume it here.
1077 public boolean onContextItemSelected(MenuItem item) {
1082 * Print the Fragments's state into the given stream.
1084 * @param prefix Text to print at the front of each line.
1085 * @param fd The raw file descriptor that the dump is being sent to.
1086 * @param writer The PrintWriter to which you should dump your state. This will be
1087 * closed for you after you return.
1088 * @param args additional arguments to the dump request.
1090 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
1091 writer.print(prefix); writer.print("mFragmentId=#");
1092 writer.print(Integer.toHexString(mFragmentId));
1093 writer.print(" mContainerId#=");
1094 writer.print(Integer.toHexString(mContainerId));
1095 writer.print(" mTag="); writer.println(mTag);
1096 writer.print(prefix); writer.print("mState="); writer.print(mState);
1097 writer.print(" mIndex="); writer.print(mIndex);
1098 writer.print(" mWho="); writer.print(mWho);
1099 writer.print(" mBackStackNesting="); writer.println(mBackStackNesting);
1100 writer.print(prefix); writer.print("mAdded="); writer.print(mAdded);
1101 writer.print(" mRemoving="); writer.print(mRemoving);
1102 writer.print(" mResumed="); writer.print(mResumed);
1103 writer.print(" mFromLayout="); writer.print(mFromLayout);
1104 writer.print(" mInLayout="); writer.println(mInLayout);
1105 writer.print(prefix); writer.print("mHidden="); writer.print(mHidden);
1106 writer.print(" mRetainInstance="); writer.print(mRetainInstance);
1107 writer.print(" mRetaining="); writer.print(mRetaining);
1108 writer.print(" mHasMenu="); writer.println(mHasMenu);
1109 if (mFragmentManager != null) {
1110 writer.print(prefix); writer.print("mFragmentManager=");
1111 writer.println(mFragmentManager);
1113 if (mImmediateActivity != null) {
1114 writer.print(prefix); writer.print("mImmediateActivity=");
1115 writer.println(mImmediateActivity);
1117 if (mActivity != null) {
1118 writer.print(prefix); writer.print("mActivity=");
1119 writer.println(mActivity);
1121 if (mArguments != null) {
1122 writer.print(prefix); writer.print("mArguments="); writer.println(mArguments);
1124 if (mSavedFragmentState != null) {
1125 writer.print(prefix); writer.print("mSavedFragmentState=");
1126 writer.println(mSavedFragmentState);
1128 if (mSavedViewState != null) {
1129 writer.print(prefix); writer.print("mSavedViewState=");
1130 writer.println(mSavedViewState);
1132 if (mTarget != null) {
1133 writer.print(prefix); writer.print("mTarget="); writer.print(mTarget);
1134 writer.print(" mTargetRequestCode=");
1135 writer.println(mTargetRequestCode);
1137 if (mNextAnim != 0) {
1138 writer.print(prefix); writer.print("mNextAnim="); writer.println(mNextAnim);
1140 if (mContainer != null) {
1141 writer.print(prefix); writer.print("mContainer="); writer.println(mContainer);
1143 if (mView != null) {
1144 writer.print(prefix); writer.print("mView="); writer.println(mView);
1146 if (mInnerView != null) {
1147 writer.print(prefix); writer.print("mInnerView="); writer.println(mView);
1149 if (mAnimatingAway != null) {
1150 writer.print(prefix); writer.print("mAnimatingAway="); writer.println(mAnimatingAway);
1151 writer.print(prefix); writer.print("mStateAfterAnimating=");
1152 writer.println(mStateAfterAnimating);
1154 if (mLoaderManager != null) {
1155 writer.print(prefix); writer.println("Loader Manager:");
1156 mLoaderManager.dump(prefix + " ", fd, writer, args);
1160 void performStop() {
1164 void performReallyStop(boolean retaining) {
1165 if (mLoadersStarted) {
1166 mLoadersStarted = false;
1167 if (!mCheckedForLoaderManager) {
1168 mCheckedForLoaderManager = true;
1169 mLoaderManager = mActivity.getLoaderManager(mIndex, mLoadersStarted, false);
1171 if (mLoaderManager != null) {
1173 mLoaderManager.doStop();
1175 mLoaderManager.doRetain();