1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.app;
18 
19 import android.animation.Animator;
20 import android.annotation.Nullable;
21 import android.content.ComponentCallbacks2;
22 import android.content.Context;
23 import android.content.Intent;
24 import android.content.res.Configuration;
25 import android.content.res.Resources;
26 import android.content.res.TypedArray;
27 import android.os.Build;
28 import android.os.Bundle;
29 import android.os.Parcel;
30 import android.os.Parcelable;
31 import android.transition.Transition;
32 import android.transition.TransitionInflater;
33 import android.transition.TransitionSet;
34 import android.util.AndroidRuntimeException;
35 import android.util.ArrayMap;
36 import android.util.AttributeSet;
37 import android.util.DebugUtils;
38 import android.util.Log;
39 import android.util.SparseArray;
40 import android.util.SuperNotCalledException;
41 import android.view.ContextMenu;
42 import android.view.ContextMenu.ContextMenuInfo;
43 import android.view.LayoutInflater;
44 import android.view.Menu;
45 import android.view.MenuInflater;
46 import android.view.MenuItem;
47 import android.view.View;
48 import android.view.View.OnCreateContextMenuListener;
49 import android.view.ViewGroup;
50 import android.widget.AdapterView;
51 
52 import java.io.FileDescriptor;
53 import java.io.PrintWriter;
54 
55 final class FragmentState implements Parcelable {
56     final String mClassName;
57     final int mIndex;
58     final boolean mFromLayout;
59     final int mFragmentId;
60     final int mContainerId;
61     final String mTag;
62     final boolean mRetainInstance;
63     final boolean mDetached;
64     final Bundle mArguments;
65 
66     Bundle mSavedFragmentState;
67 
68     Fragment mInstance;
69 
FragmentState(Fragment frag)70     public FragmentState(Fragment frag) {
71         mClassName = frag.getClass().getName();
72         mIndex = frag.mIndex;
73         mFromLayout = frag.mFromLayout;
74         mFragmentId = frag.mFragmentId;
75         mContainerId = frag.mContainerId;
76         mTag = frag.mTag;
77         mRetainInstance = frag.mRetainInstance;
78         mDetached = frag.mDetached;
79         mArguments = frag.mArguments;
80     }
81 
FragmentState(Parcel in)82     public FragmentState(Parcel in) {
83         mClassName = in.readString();
84         mIndex = in.readInt();
85         mFromLayout = in.readInt() != 0;
86         mFragmentId = in.readInt();
87         mContainerId = in.readInt();
88         mTag = in.readString();
89         mRetainInstance = in.readInt() != 0;
90         mDetached = in.readInt() != 0;
91         mArguments = in.readBundle();
92         mSavedFragmentState = in.readBundle();
93     }
94 
instantiate(Activity activity, Fragment parent)95     public Fragment instantiate(Activity activity, Fragment parent) {
96         if (mInstance != null) {
97             return mInstance;
98         }
99 
100         if (mArguments != null) {
101             mArguments.setClassLoader(activity.getClassLoader());
102         }
103 
104         mInstance = Fragment.instantiate(activity, mClassName, mArguments);
105 
106         if (mSavedFragmentState != null) {
107             mSavedFragmentState.setClassLoader(activity.getClassLoader());
108             mInstance.mSavedFragmentState = mSavedFragmentState;
109         }
110         mInstance.setIndex(mIndex, parent);
111         mInstance.mFromLayout = mFromLayout;
112         mInstance.mRestored = true;
113         mInstance.mFragmentId = mFragmentId;
114         mInstance.mContainerId = mContainerId;
115         mInstance.mTag = mTag;
116         mInstance.mRetainInstance = mRetainInstance;
117         mInstance.mDetached = mDetached;
118         mInstance.mFragmentManager = activity.mFragments;
119         if (FragmentManagerImpl.DEBUG) Log.v(FragmentManagerImpl.TAG,
120                 "Instantiated fragment " + mInstance);
121 
122         return mInstance;
123     }
124 
describeContents()125     public int describeContents() {
126         return 0;
127     }
128 
writeToParcel(Parcel dest, int flags)129     public void writeToParcel(Parcel dest, int flags) {
130         dest.writeString(mClassName);
131         dest.writeInt(mIndex);
132         dest.writeInt(mFromLayout ? 1 : 0);
133         dest.writeInt(mFragmentId);
134         dest.writeInt(mContainerId);
135         dest.writeString(mTag);
136         dest.writeInt(mRetainInstance ? 1 : 0);
137         dest.writeInt(mDetached ? 1 : 0);
138         dest.writeBundle(mArguments);
139         dest.writeBundle(mSavedFragmentState);
140     }
141 
142     public static final Parcelable.Creator<FragmentState> CREATOR
143             = new Parcelable.Creator<FragmentState>() {
144         public FragmentState createFromParcel(Parcel in) {
145             return new FragmentState(in);
146         }
147 
148         public FragmentState[] newArray(int size) {
149             return new FragmentState[size];
150         }
151     };
152 }
153 
154 /**
155  * A Fragment is a piece of an application's user interface or behavior
156  * that can be placed in an {@link Activity}.  Interaction with fragments
157  * is done through {@link FragmentManager}, which can be obtained via
158  * {@link Activity#getFragmentManager() Activity.getFragmentManager()} and
159  * {@link Fragment#getFragmentManager() Fragment.getFragmentManager()}.
160  *
161  * <p>The Fragment class can be used many ways to achieve a wide variety of
162  * results. In its core, it represents a particular operation or interface
163  * that is running within a larger {@link Activity}.  A Fragment is closely
164  * tied to the Activity it is in, and can not be used apart from one.  Though
165  * Fragment defines its own lifecycle, that lifecycle is dependent on its
166  * activity: if the activity is stopped, no fragments inside of it can be
167  * started; when the activity is destroyed, all fragments will be destroyed.
168  *
169  * <p>All subclasses of Fragment must include a public no-argument constructor.
170  * The framework will often re-instantiate a fragment class when needed,
171  * in particular during state restore, and needs to be able to find this
172  * constructor to instantiate it.  If the no-argument constructor is not
173  * available, a runtime exception will occur in some cases during state
174  * restore.
175  *
176  * <p>Topics covered here:
177  * <ol>
178  * <li><a href="#OlderPlatforms">Older Platforms</a>
179  * <li><a href="#Lifecycle">Lifecycle</a>
180  * <li><a href="#Layout">Layout</a>
181  * <li><a href="#BackStack">Back Stack</a>
182  * </ol>
183  *
184  * <div class="special reference">
185  * <h3>Developer Guides</h3>
186  * <p>For more information about using fragments, read the
187  * <a href="{@docRoot}guide/topics/fundamentals/fragments.html">Fragments</a> developer guide.</p>
188  * </div>
189  *
190  * <a name="OlderPlatforms"></a>
191  * <h3>Older Platforms</h3>
192  *
193  * While the Fragment API was introduced in
194  * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, a version of the API
195  * at is also available for use on older platforms through
196  * {@link android.support.v4.app.FragmentActivity}.  See the blog post
197  * <a href="http://android-developers.blogspot.com/2011/03/fragments-for-all.html">
198  * Fragments For All</a> for more details.
199  *
200  * <a name="Lifecycle"></a>
201  * <h3>Lifecycle</h3>
202  *
203  * <p>Though a Fragment's lifecycle is tied to its owning activity, it has
204  * its own wrinkle on the standard activity lifecycle.  It includes basic
205  * activity lifecycle methods such as {@link #onResume}, but also important
206  * are methods related to interactions with the activity and UI generation.
207  *
208  * <p>The core series of lifecycle methods that are called to bring a fragment
209  * up to resumed state (interacting with the user) are:
210  *
211  * <ol>
212  * <li> {@link #onAttach} called once the fragment is associated with its activity.
213  * <li> {@link #onCreate} called to do initial creation of the fragment.
214  * <li> {@link #onCreateView} creates and returns the view hierarchy associated
215  * with the fragment.
216  * <li> {@link #onActivityCreated} tells the fragment that its activity has
217  * completed its own {@link Activity#onCreate Activity.onCreate()}.
218  * <li> {@link #onViewStateRestored} tells the fragment that all of the saved
219  * state of its view hierarchy has been restored.
220  * <li> {@link #onStart} makes the fragment visible to the user (based on its
221  * containing activity being started).
222  * <li> {@link #onResume} makes the fragment interacting with the user (based on its
223  * containing activity being resumed).
224  * </ol>
225  *
226  * <p>As a fragment is no longer being used, it goes through a reverse
227  * series of callbacks:
228  *
229  * <ol>
230  * <li> {@link #onPause} fragment is no longer interacting with the user either
231  * because its activity is being paused or a fragment operation is modifying it
232  * in the activity.
233  * <li> {@link #onStop} fragment is no longer visible to the user either
234  * because its activity is being stopped or a fragment operation is modifying it
235  * in the activity.
236  * <li> {@link #onDestroyView} allows the fragment to clean up resources
237  * associated with its View.
238  * <li> {@link #onDestroy} called to do final cleanup of the fragment's state.
239  * <li> {@link #onDetach} called immediately prior to the fragment no longer
240  * being associated with its activity.
241  * </ol>
242  *
243  * <a name="Layout"></a>
244  * <h3>Layout</h3>
245  *
246  * <p>Fragments can be used as part of your application's layout, allowing
247  * you to better modularize your code and more easily adjust your user
248  * interface to the screen it is running on.  As an example, we can look
249  * at a simple program consisting of a list of items, and display of the
250  * details of each item.</p>
251  *
252  * <p>An activity's layout XML can include <code>&lt;fragment&gt;</code> tags
253  * to embed fragment instances inside of the layout.  For example, here is
254  * a simple layout that embeds one fragment:</p>
255  *
256  * {@sample development/samples/ApiDemos/res/layout/fragment_layout.xml layout}
257  *
258  * <p>The layout is installed in the activity in the normal way:</p>
259  *
260  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
261  *      main}
262  *
263  * <p>The titles fragment, showing a list of titles, is fairly simple, relying
264  * on {@link ListFragment} for most of its work.  Note the implementation of
265  * clicking an item: depending on the current activity's layout, it can either
266  * create and display a new fragment to show the details in-place (more about
267  * this later), or start a new activity to show the details.</p>
268  *
269  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
270  *      titles}
271  *
272  * <p>The details fragment showing the contents of a selected item just
273  * displays a string of text based on an index of a string array built in to
274  * the app:</p>
275  *
276  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
277  *      details}
278  *
279  * <p>In this case when the user clicks on a title, there is no details
280  * container in the current activity, so the titles fragment's click code will
281  * launch a new activity to display the details fragment:</p>
282  *
283  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
284  *      details_activity}
285  *
286  * <p>However the screen may be large enough to show both the list of titles
287  * and details about the currently selected title.  To use such a layout on
288  * a landscape screen, this alternative layout can be placed under layout-land:</p>
289  *
290  * {@sample development/samples/ApiDemos/res/layout-land/fragment_layout.xml layout}
291  *
292  * <p>Note how the prior code will adjust to this alternative UI flow: the titles
293  * fragment will now embed the details fragment inside of this activity, and the
294  * details activity will finish itself if it is running in a configuration
295  * where the details can be shown in-place.
296  *
297  * <p>When a configuration change causes the activity hosting these fragments
298  * to restart, its new instance may use a different layout that doesn't
299  * include the same fragments as the previous layout.  In this case all of
300  * the previous fragments will still be instantiated and running in the new
301  * instance.  However, any that are no longer associated with a &lt;fragment&gt;
302  * tag in the view hierarchy will not have their content view created
303  * and will return false from {@link #isInLayout}.  (The code here also shows
304  * how you can determine if a fragment placed in a container is no longer
305  * running in a layout with that container and avoid creating its view hierarchy
306  * in that case.)
307  *
308  * <p>The attributes of the &lt;fragment&gt; tag are used to control the
309  * LayoutParams provided when attaching the fragment's view to the parent
310  * container.  They can also be parsed by the fragment in {@link #onInflate}
311  * as parameters.
312  *
313  * <p>The fragment being instantiated must have some kind of unique identifier
314  * so that it can be re-associated with a previous instance if the parent
315  * activity needs to be destroyed and recreated.  This can be provided these
316  * ways:
317  *
318  * <ul>
319  * <li>If nothing is explicitly supplied, the view ID of the container will
320  * be used.
321  * <li><code>android:tag</code> can be used in &lt;fragment&gt; to provide
322  * a specific tag name for the fragment.
323  * <li><code>android:id</code> can be used in &lt;fragment&gt; to provide
324  * a specific identifier for the fragment.
325  * </ul>
326  *
327  * <a name="BackStack"></a>
328  * <h3>Back Stack</h3>
329  *
330  * <p>The transaction in which fragments are modified can be placed on an
331  * internal back-stack of the owning activity.  When the user presses back
332  * in the activity, any transactions on the back stack are popped off before
333  * the activity itself is finished.
334  *
335  * <p>For example, consider this simple fragment that is instantiated with
336  * an integer argument and displays that in a TextView in its UI:</p>
337  *
338  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentStack.java
339  *      fragment}
340  *
341  * <p>A function that creates a new instance of the fragment, replacing
342  * whatever current fragment instance is being shown and pushing that change
343  * on to the back stack could be written as:
344  *
345  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentStack.java
346  *      add_stack}
347  *
348  * <p>After each call to this function, a new entry is on the stack, and
349  * pressing back will pop it to return the user to whatever previous state
350  * the activity UI was in.
351  */
352 public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListener {
353     private static final ArrayMap<String, Class<?>> sClassMap =
354             new ArrayMap<String, Class<?>>();
355 
356     static final int INVALID_STATE = -1;   // Invalid state used as a null value.
357     static final int INITIALIZING = 0;     // Not yet created.
358     static final int CREATED = 1;          // Created.
359     static final int ACTIVITY_CREATED = 2; // The activity has finished its creation.
360     static final int STOPPED = 3;          // Fully created, not started.
361     static final int STARTED = 4;          // Created and started, not resumed.
362     static final int RESUMED = 5;          // Created started and resumed.
363 
364     private static final Transition USE_DEFAULT_TRANSITION = new TransitionSet();
365 
366     int mState = INITIALIZING;
367 
368     // Non-null if the fragment's view hierarchy is currently animating away,
369     // meaning we need to wait a bit on completely destroying it.  This is the
370     // animation that is running.
371     Animator mAnimatingAway;
372 
373     // If mAnimatingAway != null, this is the state we should move to once the
374     // animation is done.
375     int mStateAfterAnimating;
376 
377     // When instantiated from saved state, this is the saved state.
378     Bundle mSavedFragmentState;
379     SparseArray<Parcelable> mSavedViewState;
380 
381     // Index into active fragment array.
382     int mIndex = -1;
383 
384     // Internal unique name for this fragment;
385     String mWho;
386 
387     // Construction arguments;
388     Bundle mArguments;
389 
390     // Target fragment.
391     Fragment mTarget;
392 
393     // For use when retaining a fragment: this is the index of the last mTarget.
394     int mTargetIndex = -1;
395 
396     // Target request code.
397     int mTargetRequestCode;
398 
399     // True if the fragment is in the list of added fragments.
400     boolean mAdded;
401 
402     // If set this fragment is being removed from its activity.
403     boolean mRemoving;
404 
405     // True if the fragment is in the resumed state.
406     boolean mResumed;
407 
408     // Set to true if this fragment was instantiated from a layout file.
409     boolean mFromLayout;
410 
411     // Set to true when the view has actually been inflated in its layout.
412     boolean mInLayout;
413 
414     // True if this fragment has been restored from previously saved state.
415     boolean mRestored;
416 
417     // Number of active back stack entries this fragment is in.
418     int mBackStackNesting;
419 
420     // The fragment manager we are associated with.  Set as soon as the
421     // fragment is used in a transaction; cleared after it has been removed
422     // from all transactions.
423     FragmentManagerImpl mFragmentManager;
424 
425     // Activity this fragment is attached to.
426     Activity mActivity;
427 
428     // Private fragment manager for child fragments inside of this one.
429     FragmentManagerImpl mChildFragmentManager;
430 
431     // If this Fragment is contained in another Fragment, this is that container.
432     Fragment mParentFragment;
433 
434     // The optional identifier for this fragment -- either the container ID if it
435     // was dynamically added to the view hierarchy, or the ID supplied in
436     // layout.
437     int mFragmentId;
438 
439     // When a fragment is being dynamically added to the view hierarchy, this
440     // is the identifier of the parent container it is being added to.
441     int mContainerId;
442 
443     // The optional named tag for this fragment -- usually used to find
444     // fragments that are not part of the layout.
445     String mTag;
446 
447     // Set to true when the app has requested that this fragment be hidden
448     // from the user.
449     boolean mHidden;
450 
451     // Set to true when the app has requested that this fragment be detached.
452     boolean mDetached;
453 
454     // If set this fragment would like its instance retained across
455     // configuration changes.
456     boolean mRetainInstance;
457 
458     // If set this fragment is being retained across the current config change.
459     boolean mRetaining;
460 
461     // If set this fragment has menu items to contribute.
462     boolean mHasMenu;
463 
464     // Set to true to allow the fragment's menu to be shown.
465     boolean mMenuVisible = true;
466 
467     // Used to verify that subclasses call through to super class.
468     boolean mCalled;
469 
470     // If app has requested a specific animation, this is the one to use.
471     int mNextAnim;
472 
473     // The parent container of the fragment after dynamically added to UI.
474     ViewGroup mContainer;
475 
476     // The View generated for this fragment.
477     View mView;
478 
479     // Whether this fragment should defer starting until after other fragments
480     // have been started and their loaders are finished.
481     boolean mDeferStart;
482 
483     // Hint provided by the app that this fragment is currently visible to the user.
484     boolean mUserVisibleHint = true;
485 
486     LoaderManagerImpl mLoaderManager;
487     boolean mLoadersStarted;
488     boolean mCheckedForLoaderManager;
489 
490     private Transition mEnterTransition = null;
491     private Transition mReturnTransition = USE_DEFAULT_TRANSITION;
492     private Transition mExitTransition = null;
493     private Transition mReenterTransition = USE_DEFAULT_TRANSITION;
494     private Transition mSharedElementEnterTransition = null;
495     private Transition mSharedElementReturnTransition = USE_DEFAULT_TRANSITION;
496     private Boolean mAllowReturnTransitionOverlap;
497     private Boolean mAllowEnterTransitionOverlap;
498 
499     SharedElementCallback mEnterTransitionCallback = SharedElementCallback.NULL_CALLBACK;
500     SharedElementCallback mExitTransitionCallback = SharedElementCallback.NULL_CALLBACK;
501 
502     /**
503      * State information that has been retrieved from a fragment instance
504      * through {@link FragmentManager#saveFragmentInstanceState(Fragment)
505      * FragmentManager.saveFragmentInstanceState}.
506      */
507     public static class SavedState implements Parcelable {
508         final Bundle mState;
509 
SavedState(Bundle state)510         SavedState(Bundle state) {
511             mState = state;
512         }
513 
SavedState(Parcel in, ClassLoader loader)514         SavedState(Parcel in, ClassLoader loader) {
515             mState = in.readBundle();
516             if (loader != null && mState != null) {
517                 mState.setClassLoader(loader);
518             }
519         }
520 
521         @Override
describeContents()522         public int describeContents() {
523             return 0;
524         }
525 
526         @Override
writeToParcel(Parcel dest, int flags)527         public void writeToParcel(Parcel dest, int flags) {
528             dest.writeBundle(mState);
529         }
530 
531         public static final Parcelable.ClassLoaderCreator<SavedState> CREATOR
532                 = new Parcelable.ClassLoaderCreator<SavedState>() {
533             public SavedState createFromParcel(Parcel in) {
534                 return new SavedState(in, null);
535             }
536 
537             public SavedState createFromParcel(Parcel in, ClassLoader loader) {
538                 return new SavedState(in, loader);
539             }
540 
541             public SavedState[] newArray(int size) {
542                 return new SavedState[size];
543             }
544         };
545     }
546 
547     /**
548      * Thrown by {@link Fragment#instantiate(Context, String, Bundle)} when
549      * there is an instantiation failure.
550      */
551     static public class InstantiationException extends AndroidRuntimeException {
InstantiationException(String msg, Exception cause)552         public InstantiationException(String msg, Exception cause) {
553             super(msg, cause);
554         }
555     }
556 
557     /**
558      * Default constructor.  <strong>Every</strong> fragment must have an
559      * empty constructor, so it can be instantiated when restoring its
560      * activity's state.  It is strongly recommended that subclasses do not
561      * have other constructors with parameters, since these constructors
562      * will not be called when the fragment is re-instantiated; instead,
563      * arguments can be supplied by the caller with {@link #setArguments}
564      * and later retrieved by the Fragment with {@link #getArguments}.
565      *
566      * <p>Applications should generally not implement a constructor.  The
567      * first place application code an run where the fragment is ready to
568      * be used is in {@link #onAttach(Activity)}, the point where the fragment
569      * is actually associated with its activity.  Some applications may also
570      * want to implement {@link #onInflate} to retrieve attributes from a
571      * layout resource, though should take care here because this happens for
572      * the fragment is attached to its activity.
573      */
Fragment()574     public Fragment() {
575     }
576 
577     /**
578      * Like {@link #instantiate(Context, String, Bundle)} but with a null
579      * argument Bundle.
580      */
instantiate(Context context, String fname)581     public static Fragment instantiate(Context context, String fname) {
582         return instantiate(context, fname, null);
583     }
584 
585     /**
586      * Create a new instance of a Fragment with the given class name.  This is
587      * the same as calling its empty constructor.
588      *
589      * @param context The calling context being used to instantiate the fragment.
590      * This is currently just used to get its ClassLoader.
591      * @param fname The class name of the fragment to instantiate.
592      * @param args Bundle of arguments to supply to the fragment, which it
593      * can retrieve with {@link #getArguments()}.  May be null.
594      * @return Returns a new fragment instance.
595      * @throws InstantiationException If there is a failure in instantiating
596      * the given fragment class.  This is a runtime exception; it is not
597      * normally expected to happen.
598      */
instantiate(Context context, String fname, @Nullable Bundle args)599     public static Fragment instantiate(Context context, String fname, @Nullable Bundle args) {
600         try {
601             Class<?> clazz = sClassMap.get(fname);
602             if (clazz == null) {
603                 // Class not found in the cache, see if it's real, and try to add it
604                 clazz = context.getClassLoader().loadClass(fname);
605                 if (!Fragment.class.isAssignableFrom(clazz)) {
606                     throw new InstantiationException("Trying to instantiate a class " + fname
607                             + " that is not a Fragment", new ClassCastException());
608                 }
609                 sClassMap.put(fname, clazz);
610             }
611             Fragment f = (Fragment)clazz.newInstance();
612             if (args != null) {
613                 args.setClassLoader(f.getClass().getClassLoader());
614                 f.mArguments = args;
615             }
616             return f;
617         } catch (ClassNotFoundException e) {
618             throw new InstantiationException("Unable to instantiate fragment " + fname
619                     + ": make sure class name exists, is public, and has an"
620                     + " empty constructor that is public", e);
621         } catch (java.lang.InstantiationException e) {
622             throw new InstantiationException("Unable to instantiate fragment " + fname
623                     + ": make sure class name exists, is public, and has an"
624                     + " empty constructor that is public", e);
625         } catch (IllegalAccessException e) {
626             throw new InstantiationException("Unable to instantiate fragment " + fname
627                     + ": make sure class name exists, is public, and has an"
628                     + " empty constructor that is public", e);
629         }
630     }
631 
restoreViewState(Bundle savedInstanceState)632     final void restoreViewState(Bundle savedInstanceState) {
633         if (mSavedViewState != null) {
634             mView.restoreHierarchyState(mSavedViewState);
635             mSavedViewState = null;
636         }
637         mCalled = false;
638         onViewStateRestored(savedInstanceState);
639         if (!mCalled) {
640             throw new SuperNotCalledException("Fragment " + this
641                     + " did not call through to super.onViewStateRestored()");
642         }
643     }
644 
setIndex(int index, Fragment parent)645     final void setIndex(int index, Fragment parent) {
646         mIndex = index;
647         if (parent != null) {
648             mWho = parent.mWho + ":" + mIndex;
649         } else {
650             mWho = "android:fragment:" + mIndex;
651         }
652     }
653 
isInBackStack()654     final boolean isInBackStack() {
655         return mBackStackNesting > 0;
656     }
657 
658     /**
659      * Subclasses can not override equals().
660      */
equals(Object o)661     @Override final public boolean equals(Object o) {
662         return super.equals(o);
663     }
664 
665     /**
666      * Subclasses can not override hashCode().
667      */
hashCode()668     @Override final public int hashCode() {
669         return super.hashCode();
670     }
671 
672     @Override
toString()673     public String toString() {
674         StringBuilder sb = new StringBuilder(128);
675         DebugUtils.buildShortClassTag(this, sb);
676         if (mIndex >= 0) {
677             sb.append(" #");
678             sb.append(mIndex);
679         }
680         if (mFragmentId != 0) {
681             sb.append(" id=0x");
682             sb.append(Integer.toHexString(mFragmentId));
683         }
684         if (mTag != null) {
685             sb.append(" ");
686             sb.append(mTag);
687         }
688         sb.append('}');
689         return sb.toString();
690     }
691 
692     /**
693      * Return the identifier this fragment is known by.  This is either
694      * the android:id value supplied in a layout or the container view ID
695      * supplied when adding the fragment.
696      */
getId()697     final public int getId() {
698         return mFragmentId;
699     }
700 
701     /**
702      * Get the tag name of the fragment, if specified.
703      */
getTag()704     final public String getTag() {
705         return mTag;
706     }
707 
708     /**
709      * Supply the construction arguments for this fragment.  This can only
710      * be called before the fragment has been attached to its activity; that
711      * is, you should call it immediately after constructing the fragment.  The
712      * arguments supplied here will be retained across fragment destroy and
713      * creation.
714      */
setArguments(Bundle args)715     public void setArguments(Bundle args) {
716         if (mIndex >= 0) {
717             throw new IllegalStateException("Fragment already active");
718         }
719         mArguments = args;
720     }
721 
722     /**
723      * Return the arguments supplied when the fragment was instantiated,
724      * if any.
725      */
getArguments()726     final public Bundle getArguments() {
727         return mArguments;
728     }
729 
730     /**
731      * Set the initial saved state that this Fragment should restore itself
732      * from when first being constructed, as returned by
733      * {@link FragmentManager#saveFragmentInstanceState(Fragment)
734      * FragmentManager.saveFragmentInstanceState}.
735      *
736      * @param state The state the fragment should be restored from.
737      */
setInitialSavedState(SavedState state)738     public void setInitialSavedState(SavedState state) {
739         if (mIndex >= 0) {
740             throw new IllegalStateException("Fragment already active");
741         }
742         mSavedFragmentState = state != null && state.mState != null
743                 ? state.mState : null;
744     }
745 
746     /**
747      * Optional target for this fragment.  This may be used, for example,
748      * if this fragment is being started by another, and when done wants to
749      * give a result back to the first.  The target set here is retained
750      * across instances via {@link FragmentManager#putFragment
751      * FragmentManager.putFragment()}.
752      *
753      * @param fragment The fragment that is the target of this one.
754      * @param requestCode Optional request code, for convenience if you
755      * are going to call back with {@link #onActivityResult(int, int, Intent)}.
756      */
setTargetFragment(Fragment fragment, int requestCode)757     public void setTargetFragment(Fragment fragment, int requestCode) {
758         mTarget = fragment;
759         mTargetRequestCode = requestCode;
760     }
761 
762     /**
763      * Return the target fragment set by {@link #setTargetFragment}.
764      */
getTargetFragment()765     final public Fragment getTargetFragment() {
766         return mTarget;
767     }
768 
769     /**
770      * Return the target request code set by {@link #setTargetFragment}.
771      */
getTargetRequestCode()772     final public int getTargetRequestCode() {
773         return mTargetRequestCode;
774     }
775 
776     /**
777      * Return the Activity this fragment is currently associated with.
778      */
getActivity()779     final public Activity getActivity() {
780         return mActivity;
781     }
782 
783     /**
784      * Return <code>getActivity().getResources()</code>.
785      */
getResources()786     final public Resources getResources() {
787         if (mActivity == null) {
788             throw new IllegalStateException("Fragment " + this + " not attached to Activity");
789         }
790         return mActivity.getResources();
791     }
792 
793     /**
794      * Return a localized, styled CharSequence from the application's package's
795      * default string table.
796      *
797      * @param resId Resource id for the CharSequence text
798      */
getText(int resId)799     public final CharSequence getText(int resId) {
800         return getResources().getText(resId);
801     }
802 
803     /**
804      * Return a localized string from the application's package's
805      * default string table.
806      *
807      * @param resId Resource id for the string
808      */
getString(int resId)809     public final String getString(int resId) {
810         return getResources().getString(resId);
811     }
812 
813     /**
814      * Return a localized formatted string from the application's package's
815      * default string table, substituting the format arguments as defined in
816      * {@link java.util.Formatter} and {@link java.lang.String#format}.
817      *
818      * @param resId Resource id for the format string
819      * @param formatArgs The format arguments that will be used for substitution.
820      */
821 
getString(int resId, Object... formatArgs)822     public final String getString(int resId, Object... formatArgs) {
823         return getResources().getString(resId, formatArgs);
824     }
825 
826     /**
827      * Return the FragmentManager for interacting with fragments associated
828      * with this fragment's activity.  Note that this will be non-null slightly
829      * before {@link #getActivity()}, during the time from when the fragment is
830      * placed in a {@link FragmentTransaction} until it is committed and
831      * attached to its activity.
832      *
833      * <p>If this Fragment is a child of another Fragment, the FragmentManager
834      * returned here will be the parent's {@link #getChildFragmentManager()}.
835      */
getFragmentManager()836     final public FragmentManager getFragmentManager() {
837         return mFragmentManager;
838     }
839 
840     /**
841      * Return a private FragmentManager for placing and managing Fragments
842      * inside of this Fragment.
843      */
getChildFragmentManager()844     final public FragmentManager getChildFragmentManager() {
845         if (mChildFragmentManager == null) {
846             instantiateChildFragmentManager();
847             if (mState >= RESUMED) {
848                 mChildFragmentManager.dispatchResume();
849             } else if (mState >= STARTED) {
850                 mChildFragmentManager.dispatchStart();
851             } else if (mState >= ACTIVITY_CREATED) {
852                 mChildFragmentManager.dispatchActivityCreated();
853             } else if (mState >= CREATED) {
854                 mChildFragmentManager.dispatchCreate();
855             }
856         }
857         return mChildFragmentManager;
858     }
859 
860     /**
861      * Returns the parent Fragment containing this Fragment.  If this Fragment
862      * is attached directly to an Activity, returns null.
863      */
getParentFragment()864     final public Fragment getParentFragment() {
865         return mParentFragment;
866     }
867 
868     /**
869      * Return true if the fragment is currently added to its activity.
870      */
isAdded()871     final public boolean isAdded() {
872         return mActivity != null && mAdded;
873     }
874 
875     /**
876      * Return true if the fragment has been explicitly detached from the UI.
877      * That is, {@link FragmentTransaction#detach(Fragment)
878      * FragmentTransaction.detach(Fragment)} has been used on it.
879      */
isDetached()880     final public boolean isDetached() {
881         return mDetached;
882     }
883 
884     /**
885      * Return true if this fragment is currently being removed from its
886      * activity.  This is  <em>not</em> whether its activity is finishing, but
887      * rather whether it is in the process of being removed from its activity.
888      */
isRemoving()889     final public boolean isRemoving() {
890         return mRemoving;
891     }
892 
893     /**
894      * Return true if the layout is included as part of an activity view
895      * hierarchy via the &lt;fragment&gt; tag.  This will always be true when
896      * fragments are created through the &lt;fragment&gt; tag, <em>except</em>
897      * in the case where an old fragment is restored from a previous state and
898      * it does not appear in the layout of the current state.
899      */
isInLayout()900     final public boolean isInLayout() {
901         return mInLayout;
902     }
903 
904     /**
905      * Return true if the fragment is in the resumed state.  This is true
906      * for the duration of {@link #onResume()} and {@link #onPause()} as well.
907      */
isResumed()908     final public boolean isResumed() {
909         return mResumed;
910     }
911 
912     /**
913      * Return true if the fragment is currently visible to the user.  This means
914      * it: (1) has been added, (2) has its view attached to the window, and
915      * (3) is not hidden.
916      */
isVisible()917     final public boolean isVisible() {
918         return isAdded() && !isHidden() && mView != null
919                 && mView.getWindowToken() != null && mView.getVisibility() == View.VISIBLE;
920     }
921 
922     /**
923      * Return true if the fragment has been hidden.  By default fragments
924      * are shown.  You can find out about changes to this state with
925      * {@link #onHiddenChanged}.  Note that the hidden state is orthogonal
926      * to other states -- that is, to be visible to the user, a fragment
927      * must be both started and not hidden.
928      */
isHidden()929     final public boolean isHidden() {
930         return mHidden;
931     }
932 
933     /**
934      * Called when the hidden state (as returned by {@link #isHidden()} of
935      * the fragment has changed.  Fragments start out not hidden; this will
936      * be called whenever the fragment changes state from that.
937      * @param hidden True if the fragment is now hidden, false if it is not
938      * visible.
939      */
onHiddenChanged(boolean hidden)940     public void onHiddenChanged(boolean hidden) {
941     }
942 
943     /**
944      * Control whether a fragment instance is retained across Activity
945      * re-creation (such as from a configuration change).  This can only
946      * be used with fragments not in the back stack.  If set, the fragment
947      * lifecycle will be slightly different when an activity is recreated:
948      * <ul>
949      * <li> {@link #onDestroy()} will not be called (but {@link #onDetach()} still
950      * will be, because the fragment is being detached from its current activity).
951      * <li> {@link #onCreate(Bundle)} will not be called since the fragment
952      * is not being re-created.
953      * <li> {@link #onAttach(Activity)} and {@link #onActivityCreated(Bundle)} <b>will</b>
954      * still be called.
955      * </ul>
956      */
setRetainInstance(boolean retain)957     public void setRetainInstance(boolean retain) {
958         if (retain && mParentFragment != null) {
959             throw new IllegalStateException(
960                     "Can't retain fragements that are nested in other fragments");
961         }
962         mRetainInstance = retain;
963     }
964 
getRetainInstance()965     final public boolean getRetainInstance() {
966         return mRetainInstance;
967     }
968 
969     /**
970      * Report that this fragment would like to participate in populating
971      * the options menu by receiving a call to {@link #onCreateOptionsMenu}
972      * and related methods.
973      *
974      * @param hasMenu If true, the fragment has menu items to contribute.
975      */
setHasOptionsMenu(boolean hasMenu)976     public void setHasOptionsMenu(boolean hasMenu) {
977         if (mHasMenu != hasMenu) {
978             mHasMenu = hasMenu;
979             if (isAdded() && !isHidden()) {
980                 mFragmentManager.invalidateOptionsMenu();
981             }
982         }
983     }
984 
985     /**
986      * Set a hint for whether this fragment's menu should be visible.  This
987      * is useful if you know that a fragment has been placed in your view
988      * hierarchy so that the user can not currently seen it, so any menu items
989      * it has should also not be shown.
990      *
991      * @param menuVisible The default is true, meaning the fragment's menu will
992      * be shown as usual.  If false, the user will not see the menu.
993      */
setMenuVisibility(boolean menuVisible)994     public void setMenuVisibility(boolean menuVisible) {
995         if (mMenuVisible != menuVisible) {
996             mMenuVisible = menuVisible;
997             if (mHasMenu && isAdded() && !isHidden()) {
998                 mFragmentManager.invalidateOptionsMenu();
999             }
1000         }
1001     }
1002 
1003     /**
1004      * Set a hint to the system about whether this fragment's UI is currently visible
1005      * to the user. This hint defaults to true and is persistent across fragment instance
1006      * state save and restore.
1007      *
1008      * <p>An app may set this to false to indicate that the fragment's UI is
1009      * scrolled out of visibility or is otherwise not directly visible to the user.
1010      * This may be used by the system to prioritize operations such as fragment lifecycle updates
1011      * or loader ordering behavior.</p>
1012      *
1013      * @param isVisibleToUser true if this fragment's UI is currently visible to the user (default),
1014      *                        false if it is not.
1015      */
setUserVisibleHint(boolean isVisibleToUser)1016     public void setUserVisibleHint(boolean isVisibleToUser) {
1017         if (!mUserVisibleHint && isVisibleToUser && mState < STARTED) {
1018             mFragmentManager.performPendingDeferredStart(this);
1019         }
1020         mUserVisibleHint = isVisibleToUser;
1021         mDeferStart = !isVisibleToUser;
1022     }
1023 
1024     /**
1025      * @return The current value of the user-visible hint on this fragment.
1026      * @see #setUserVisibleHint(boolean)
1027      */
getUserVisibleHint()1028     public boolean getUserVisibleHint() {
1029         return mUserVisibleHint;
1030     }
1031 
1032     /**
1033      * Return the LoaderManager for this fragment, creating it if needed.
1034      */
getLoaderManager()1035     public LoaderManager getLoaderManager() {
1036         if (mLoaderManager != null) {
1037             return mLoaderManager;
1038         }
1039         if (mActivity == null) {
1040             throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1041         }
1042         mCheckedForLoaderManager = true;
1043         mLoaderManager = mActivity.getLoaderManager(mWho, mLoadersStarted, true);
1044         return mLoaderManager;
1045     }
1046 
1047     /**
1048      * Call {@link Activity#startActivity(Intent)} from the fragment's
1049      * containing Activity.
1050      *
1051      * @param intent The intent to start.
1052      */
startActivity(Intent intent)1053     public void startActivity(Intent intent) {
1054         startActivity(intent, null);
1055     }
1056 
1057     /**
1058      * Call {@link Activity#startActivity(Intent, Bundle)} from the fragment's
1059      * containing Activity.
1060      *
1061      * @param intent The intent to start.
1062      * @param options Additional options for how the Activity should be started.
1063      * See {@link android.content.Context#startActivity(Intent, Bundle)
1064      * Context.startActivity(Intent, Bundle)} for more details.
1065      */
startActivity(Intent intent, Bundle options)1066     public void startActivity(Intent intent, Bundle options) {
1067         if (mActivity == null) {
1068             throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1069         }
1070         if (options != null) {
1071             mActivity.startActivityFromFragment(this, intent, -1, options);
1072         } else {
1073             // Note we want to go through this call for compatibility with
1074             // applications that may have overridden the method.
1075             mActivity.startActivityFromFragment(this, intent, -1);
1076         }
1077     }
1078 
1079     /**
1080      * Call {@link Activity#startActivityForResult(Intent, int)} from the fragment's
1081      * containing Activity.
1082      */
startActivityForResult(Intent intent, int requestCode)1083     public void startActivityForResult(Intent intent, int requestCode) {
1084         startActivityForResult(intent, requestCode, null);
1085     }
1086 
1087     /**
1088      * Call {@link Activity#startActivityForResult(Intent, int, Bundle)} from the fragment's
1089      * containing Activity.
1090      */
startActivityForResult(Intent intent, int requestCode, Bundle options)1091     public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
1092         if (mActivity == null) {
1093             throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1094         }
1095         if (options != null) {
1096             mActivity.startActivityFromFragment(this, intent, requestCode, options);
1097         } else {
1098             // Note we want to go through this call for compatibility with
1099             // applications that may have overridden the method.
1100             mActivity.startActivityFromFragment(this, intent, requestCode, options);
1101         }
1102     }
1103 
1104     /**
1105      * Receive the result from a previous call to
1106      * {@link #startActivityForResult(Intent, int)}.  This follows the
1107      * related Activity API as described there in
1108      * {@link Activity#onActivityResult(int, int, Intent)}.
1109      *
1110      * @param requestCode The integer request code originally supplied to
1111      *                    startActivityForResult(), allowing you to identify who this
1112      *                    result came from.
1113      * @param resultCode The integer result code returned by the child activity
1114      *                   through its setResult().
1115      * @param data An Intent, which can return result data to the caller
1116      *               (various data can be attached to Intent "extras").
1117      */
onActivityResult(int requestCode, int resultCode, Intent data)1118     public void onActivityResult(int requestCode, int resultCode, Intent data) {
1119     }
1120 
1121     /**
1122      * @hide Hack so that DialogFragment can make its Dialog before creating
1123      * its views, and the view construction can use the dialog's context for
1124      * inflation.  Maybe this should become a public API. Note sure.
1125      */
getLayoutInflater(Bundle savedInstanceState)1126     public LayoutInflater getLayoutInflater(Bundle savedInstanceState) {
1127         // Newer platform versions use the child fragment manager's LayoutInflaterFactory.
1128         if (mActivity.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
1129             LayoutInflater result = mActivity.getLayoutInflater().cloneInContext(mActivity);
1130             getChildFragmentManager(); // Init if needed; use raw implementation below.
1131             result.setPrivateFactory(mChildFragmentManager.getLayoutInflaterFactory());
1132             return result;
1133         } else {
1134             return mActivity.getLayoutInflater();
1135         }
1136     }
1137 
1138     /**
1139      * @deprecated Use {@link #onInflate(Activity, AttributeSet, Bundle)} instead.
1140      */
1141     @Deprecated
onInflate(AttributeSet attrs, Bundle savedInstanceState)1142     public void onInflate(AttributeSet attrs, Bundle savedInstanceState) {
1143         mCalled = true;
1144     }
1145 
1146     /**
1147      * Called when a fragment is being created as part of a view layout
1148      * inflation, typically from setting the content view of an activity.  This
1149      * may be called immediately after the fragment is created from a <fragment>
1150      * tag in a layout file.  Note this is <em>before</em> the fragment's
1151      * {@link #onAttach(Activity)} has been called; all you should do here is
1152      * parse the attributes and save them away.
1153      *
1154      * <p>This is called every time the fragment is inflated, even if it is
1155      * being inflated into a new instance with saved state.  It typically makes
1156      * sense to re-parse the parameters each time, to allow them to change with
1157      * different configurations.</p>
1158      *
1159      * <p>Here is a typical implementation of a fragment that can take parameters
1160      * both through attributes supplied here as well from {@link #getArguments()}:</p>
1161      *
1162      * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
1163      *      fragment}
1164      *
1165      * <p>Note that parsing the XML attributes uses a "styleable" resource.  The
1166      * declaration for the styleable used here is:</p>
1167      *
1168      * {@sample development/samples/ApiDemos/res/values/attrs.xml fragment_arguments}
1169      *
1170      * <p>The fragment can then be declared within its activity's content layout
1171      * through a tag like this:</p>
1172      *
1173      * {@sample development/samples/ApiDemos/res/layout/fragment_arguments.xml from_attributes}
1174      *
1175      * <p>This fragment can also be created dynamically from arguments given
1176      * at runtime in the arguments Bundle; here is an example of doing so at
1177      * creation of the containing activity:</p>
1178      *
1179      * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
1180      *      create}
1181      *
1182      * @param activity The Activity that is inflating this fragment.
1183      * @param attrs The attributes at the tag where the fragment is
1184      * being created.
1185      * @param savedInstanceState If the fragment is being re-created from
1186      * a previous saved state, this is the state.
1187      */
onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState)1188     public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
1189         onInflate(attrs, savedInstanceState);
1190         mCalled = true;
1191 
1192         TypedArray a = activity.obtainStyledAttributes(attrs,
1193                 com.android.internal.R.styleable.Fragment);
1194         mEnterTransition = loadTransition(activity, a, mEnterTransition, null,
1195                 com.android.internal.R.styleable.Fragment_fragmentEnterTransition);
1196         mReturnTransition = loadTransition(activity, a, mReturnTransition, USE_DEFAULT_TRANSITION,
1197                 com.android.internal.R.styleable.Fragment_fragmentReturnTransition);
1198         mExitTransition = loadTransition(activity, a, mExitTransition, null,
1199                 com.android.internal.R.styleable.Fragment_fragmentExitTransition);
1200         mReenterTransition = loadTransition(activity, a, mReenterTransition, USE_DEFAULT_TRANSITION,
1201                 com.android.internal.R.styleable.Fragment_fragmentReenterTransition);
1202         mSharedElementEnterTransition = loadTransition(activity, a, mSharedElementEnterTransition,
1203                 null, com.android.internal.R.styleable.Fragment_fragmentSharedElementEnterTransition);
1204         mSharedElementReturnTransition = loadTransition(activity, a, mSharedElementReturnTransition,
1205                 USE_DEFAULT_TRANSITION,
1206                 com.android.internal.R.styleable.Fragment_fragmentSharedElementReturnTransition);
1207         if (mAllowEnterTransitionOverlap == null) {
1208             mAllowEnterTransitionOverlap = a.getBoolean(
1209                     com.android.internal.R.styleable.Fragment_fragmentAllowEnterTransitionOverlap, true);
1210         }
1211         if (mAllowReturnTransitionOverlap == null) {
1212             mAllowReturnTransitionOverlap = a.getBoolean(
1213                     com.android.internal.R.styleable.Fragment_fragmentAllowReturnTransitionOverlap, true);
1214         }
1215         a.recycle();
1216     }
1217 
1218     /**
1219      * Called when a fragment is first attached to its activity.
1220      * {@link #onCreate(Bundle)} will be called after this.
1221      */
onAttach(Activity activity)1222     public void onAttach(Activity activity) {
1223         mCalled = true;
1224     }
1225 
1226     /**
1227      * Called when a fragment loads an animation.
1228      */
onCreateAnimator(int transit, boolean enter, int nextAnim)1229     public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) {
1230         return null;
1231     }
1232 
1233     /**
1234      * Called to do initial creation of a fragment.  This is called after
1235      * {@link #onAttach(Activity)} and before
1236      * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
1237      *
1238      * <p>Note that this can be called while the fragment's activity is
1239      * still in the process of being created.  As such, you can not rely
1240      * on things like the activity's content view hierarchy being initialized
1241      * at this point.  If you want to do work once the activity itself is
1242      * created, see {@link #onActivityCreated(Bundle)}.
1243      *
1244      * @param savedInstanceState If the fragment is being re-created from
1245      * a previous saved state, this is the state.
1246      */
onCreate(Bundle savedInstanceState)1247     public void onCreate(Bundle savedInstanceState) {
1248         mCalled = true;
1249     }
1250 
1251     /**
1252      * Called to have the fragment instantiate its user interface view.
1253      * This is optional, and non-graphical fragments can return null (which
1254      * is the default implementation).  This will be called between
1255      * {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}.
1256      *
1257      * <p>If you return a View from here, you will later be called in
1258      * {@link #onDestroyView} when the view is being released.
1259      *
1260      * @param inflater The LayoutInflater object that can be used to inflate
1261      * any views in the fragment,
1262      * @param container If non-null, this is the parent view that the fragment's
1263      * UI should be attached to.  The fragment should not add the view itself,
1264      * but this can be used to generate the LayoutParams of the view.
1265      * @param savedInstanceState If non-null, this fragment is being re-constructed
1266      * from a previous saved state as given here.
1267      *
1268      * @return Return the View for the fragment's UI, or null.
1269      */
1270     @Nullable
onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState)1271     public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
1272             Bundle savedInstanceState) {
1273         return null;
1274     }
1275 
1276     /**
1277      * Called immediately after {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}
1278      * has returned, but before any saved state has been restored in to the view.
1279      * This gives subclasses a chance to initialize themselves once
1280      * they know their view hierarchy has been completely created.  The fragment's
1281      * view hierarchy is not however attached to its parent at this point.
1282      * @param view The View returned by {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
1283      * @param savedInstanceState If non-null, this fragment is being re-constructed
1284      * from a previous saved state as given here.
1285      */
onViewCreated(View view, @Nullable Bundle savedInstanceState)1286     public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
1287     }
1288 
1289     /**
1290      * Get the root view for the fragment's layout (the one returned by {@link #onCreateView}),
1291      * if provided.
1292      *
1293      * @return The fragment's root view, or null if it has no layout.
1294      */
1295     @Nullable
getView()1296     public View getView() {
1297         return mView;
1298     }
1299 
1300     /**
1301      * Called when the fragment's activity has been created and this
1302      * fragment's view hierarchy instantiated.  It can be used to do final
1303      * initialization once these pieces are in place, such as retrieving
1304      * views or restoring state.  It is also useful for fragments that use
1305      * {@link #setRetainInstance(boolean)} to retain their instance,
1306      * as this callback tells the fragment when it is fully associated with
1307      * the new activity instance.  This is called after {@link #onCreateView}
1308      * and before {@link #onViewStateRestored(Bundle)}.
1309      *
1310      * @param savedInstanceState If the fragment is being re-created from
1311      * a previous saved state, this is the state.
1312      */
onActivityCreated(Bundle savedInstanceState)1313     public void onActivityCreated(Bundle savedInstanceState) {
1314         mCalled = true;
1315     }
1316 
1317     /**
1318      * Called when all saved state has been restored into the view hierarchy
1319      * of the fragment.  This can be used to do initialization based on saved
1320      * state that you are letting the view hierarchy track itself, such as
1321      * whether check box widgets are currently checked.  This is called
1322      * after {@link #onActivityCreated(Bundle)} and before
1323      * {@link #onStart()}.
1324      *
1325      * @param savedInstanceState If the fragment is being re-created from
1326      * a previous saved state, this is the state.
1327      */
onViewStateRestored(Bundle savedInstanceState)1328     public void onViewStateRestored(Bundle savedInstanceState) {
1329         mCalled = true;
1330     }
1331 
1332     /**
1333      * Called when the Fragment is visible to the user.  This is generally
1334      * tied to {@link Activity#onStart() Activity.onStart} of the containing
1335      * Activity's lifecycle.
1336      */
onStart()1337     public void onStart() {
1338         mCalled = true;
1339 
1340         if (!mLoadersStarted) {
1341             mLoadersStarted = true;
1342             if (!mCheckedForLoaderManager) {
1343                 mCheckedForLoaderManager = true;
1344                 mLoaderManager = mActivity.getLoaderManager(mWho, mLoadersStarted, false);
1345             }
1346             if (mLoaderManager != null) {
1347                 mLoaderManager.doStart();
1348             }
1349         }
1350     }
1351 
1352     /**
1353      * Called when the fragment is visible to the user and actively running.
1354      * This is generally
1355      * tied to {@link Activity#onResume() Activity.onResume} of the containing
1356      * Activity's lifecycle.
1357      */
onResume()1358     public void onResume() {
1359         mCalled = true;
1360     }
1361 
1362     /**
1363      * Called to ask the fragment to save its current dynamic state, so it
1364      * can later be reconstructed in a new instance of its process is
1365      * restarted.  If a new instance of the fragment later needs to be
1366      * created, the data you place in the Bundle here will be available
1367      * in the Bundle given to {@link #onCreate(Bundle)},
1368      * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}, and
1369      * {@link #onActivityCreated(Bundle)}.
1370      *
1371      * <p>This corresponds to {@link Activity#onSaveInstanceState(Bundle)
1372      * Activity.onSaveInstanceState(Bundle)} and most of the discussion there
1373      * applies here as well.  Note however: <em>this method may be called
1374      * at any time before {@link #onDestroy()}</em>.  There are many situations
1375      * where a fragment may be mostly torn down (such as when placed on the
1376      * back stack with no UI showing), but its state will not be saved until
1377      * its owning activity actually needs to save its state.
1378      *
1379      * @param outState Bundle in which to place your saved state.
1380      */
onSaveInstanceState(Bundle outState)1381     public void onSaveInstanceState(Bundle outState) {
1382     }
1383 
onConfigurationChanged(Configuration newConfig)1384     public void onConfigurationChanged(Configuration newConfig) {
1385         mCalled = true;
1386     }
1387 
1388     /**
1389      * Called when the Fragment is no longer resumed.  This is generally
1390      * tied to {@link Activity#onPause() Activity.onPause} of the containing
1391      * Activity's lifecycle.
1392      */
onPause()1393     public void onPause() {
1394         mCalled = true;
1395     }
1396 
1397     /**
1398      * Called when the Fragment is no longer started.  This is generally
1399      * tied to {@link Activity#onStop() Activity.onStop} of the containing
1400      * Activity's lifecycle.
1401      */
onStop()1402     public void onStop() {
1403         mCalled = true;
1404     }
1405 
onLowMemory()1406     public void onLowMemory() {
1407         mCalled = true;
1408     }
1409 
onTrimMemory(int level)1410     public void onTrimMemory(int level) {
1411         mCalled = true;
1412     }
1413 
1414     /**
1415      * Called when the view previously created by {@link #onCreateView} has
1416      * been detached from the fragment.  The next time the fragment needs
1417      * to be displayed, a new view will be created.  This is called
1418      * after {@link #onStop()} and before {@link #onDestroy()}.  It is called
1419      * <em>regardless</em> of whether {@link #onCreateView} returned a
1420      * non-null view.  Internally it is called after the view's state has
1421      * been saved but before it has been removed from its parent.
1422      */
onDestroyView()1423     public void onDestroyView() {
1424         mCalled = true;
1425     }
1426 
1427     /**
1428      * Called when the fragment is no longer in use.  This is called
1429      * after {@link #onStop()} and before {@link #onDetach()}.
1430      */
onDestroy()1431     public void onDestroy() {
1432         mCalled = true;
1433         //Log.v("foo", "onDestroy: mCheckedForLoaderManager=" + mCheckedForLoaderManager
1434         //        + " mLoaderManager=" + mLoaderManager);
1435         if (!mCheckedForLoaderManager) {
1436             mCheckedForLoaderManager = true;
1437             mLoaderManager = mActivity.getLoaderManager(mWho, mLoadersStarted, false);
1438         }
1439         if (mLoaderManager != null) {
1440             mLoaderManager.doDestroy();
1441         }
1442     }
1443 
1444     /**
1445      * Called by the fragment manager once this fragment has been removed,
1446      * so that we don't have any left-over state if the application decides
1447      * to re-use the instance.  This only clears state that the framework
1448      * internally manages, not things the application sets.
1449      */
initState()1450     void initState() {
1451         mIndex = -1;
1452         mWho = null;
1453         mAdded = false;
1454         mRemoving = false;
1455         mResumed = false;
1456         mFromLayout = false;
1457         mInLayout = false;
1458         mRestored = false;
1459         mBackStackNesting = 0;
1460         mFragmentManager = null;
1461         mChildFragmentManager = null;
1462         mActivity = null;
1463         mFragmentId = 0;
1464         mContainerId = 0;
1465         mTag = null;
1466         mHidden = false;
1467         mDetached = false;
1468         mRetaining = false;
1469         mLoaderManager = null;
1470         mLoadersStarted = false;
1471         mCheckedForLoaderManager = false;
1472     }
1473 
1474     /**
1475      * Called when the fragment is no longer attached to its activity.  This
1476      * is called after {@link #onDestroy()}.
1477      */
onDetach()1478     public void onDetach() {
1479         mCalled = true;
1480     }
1481 
1482     /**
1483      * Initialize the contents of the Activity's standard options menu.  You
1484      * should place your menu items in to <var>menu</var>.  For this method
1485      * to be called, you must have first called {@link #setHasOptionsMenu}.  See
1486      * {@link Activity#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu}
1487      * for more information.
1488      *
1489      * @param menu The options menu in which you place your items.
1490      *
1491      * @see #setHasOptionsMenu
1492      * @see #onPrepareOptionsMenu
1493      * @see #onOptionsItemSelected
1494      */
onCreateOptionsMenu(Menu menu, MenuInflater inflater)1495     public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
1496     }
1497 
1498     /**
1499      * Prepare the Screen's standard options menu to be displayed.  This is
1500      * called right before the menu is shown, every time it is shown.  You can
1501      * use this method to efficiently enable/disable items or otherwise
1502      * dynamically modify the contents.  See
1503      * {@link Activity#onPrepareOptionsMenu(Menu) Activity.onPrepareOptionsMenu}
1504      * for more information.
1505      *
1506      * @param menu The options menu as last shown or first initialized by
1507      *             onCreateOptionsMenu().
1508      *
1509      * @see #setHasOptionsMenu
1510      * @see #onCreateOptionsMenu
1511      */
onPrepareOptionsMenu(Menu menu)1512     public void onPrepareOptionsMenu(Menu menu) {
1513     }
1514 
1515     /**
1516      * Called when this fragment's option menu items are no longer being
1517      * included in the overall options menu.  Receiving this call means that
1518      * the menu needed to be rebuilt, but this fragment's items were not
1519      * included in the newly built menu (its {@link #onCreateOptionsMenu(Menu, MenuInflater)}
1520      * was not called).
1521      */
onDestroyOptionsMenu()1522     public void onDestroyOptionsMenu() {
1523     }
1524 
1525     /**
1526      * This hook is called whenever an item in your options menu is selected.
1527      * The default implementation simply returns false to have the normal
1528      * processing happen (calling the item's Runnable or sending a message to
1529      * its Handler as appropriate).  You can use this method for any items
1530      * for which you would like to do processing without those other
1531      * facilities.
1532      *
1533      * <p>Derived classes should call through to the base class for it to
1534      * perform the default menu handling.
1535      *
1536      * @param item The menu item that was selected.
1537      *
1538      * @return boolean Return false to allow normal menu processing to
1539      *         proceed, true to consume it here.
1540      *
1541      * @see #onCreateOptionsMenu
1542      */
onOptionsItemSelected(MenuItem item)1543     public boolean onOptionsItemSelected(MenuItem item) {
1544         return false;
1545     }
1546 
1547     /**
1548      * This hook is called whenever the options menu is being closed (either by the user canceling
1549      * the menu with the back/menu button, or when an item is selected).
1550      *
1551      * @param menu The options menu as last shown or first initialized by
1552      *             onCreateOptionsMenu().
1553      */
onOptionsMenuClosed(Menu menu)1554     public void onOptionsMenuClosed(Menu menu) {
1555     }
1556 
1557     /**
1558      * Called when a context menu for the {@code view} is about to be shown.
1559      * Unlike {@link #onCreateOptionsMenu}, this will be called every
1560      * time the context menu is about to be shown and should be populated for
1561      * the view (or item inside the view for {@link AdapterView} subclasses,
1562      * this can be found in the {@code menuInfo})).
1563      * <p>
1564      * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
1565      * item has been selected.
1566      * <p>
1567      * The default implementation calls up to
1568      * {@link Activity#onCreateContextMenu Activity.onCreateContextMenu}, though
1569      * you can not call this implementation if you don't want that behavior.
1570      * <p>
1571      * It is not safe to hold onto the context menu after this method returns.
1572      * {@inheritDoc}
1573      */
onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)1574     public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1575         getActivity().onCreateContextMenu(menu, v, menuInfo);
1576     }
1577 
1578     /**
1579      * Registers a context menu to be shown for the given view (multiple views
1580      * can show the context menu). This method will set the
1581      * {@link OnCreateContextMenuListener} on the view to this fragment, so
1582      * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
1583      * called when it is time to show the context menu.
1584      *
1585      * @see #unregisterForContextMenu(View)
1586      * @param view The view that should show a context menu.
1587      */
registerForContextMenu(View view)1588     public void registerForContextMenu(View view) {
1589         view.setOnCreateContextMenuListener(this);
1590     }
1591 
1592     /**
1593      * Prevents a context menu to be shown for the given view. This method will
1594      * remove the {@link OnCreateContextMenuListener} on the view.
1595      *
1596      * @see #registerForContextMenu(View)
1597      * @param view The view that should stop showing a context menu.
1598      */
unregisterForContextMenu(View view)1599     public void unregisterForContextMenu(View view) {
1600         view.setOnCreateContextMenuListener(null);
1601     }
1602 
1603     /**
1604      * This hook is called whenever an item in a context menu is selected. The
1605      * default implementation simply returns false to have the normal processing
1606      * happen (calling the item's Runnable or sending a message to its Handler
1607      * as appropriate). You can use this method for any items for which you
1608      * would like to do processing without those other facilities.
1609      * <p>
1610      * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
1611      * View that added this menu item.
1612      * <p>
1613      * Derived classes should call through to the base class for it to perform
1614      * the default menu handling.
1615      *
1616      * @param item The context menu item that was selected.
1617      * @return boolean Return false to allow normal context menu processing to
1618      *         proceed, true to consume it here.
1619      */
onContextItemSelected(MenuItem item)1620     public boolean onContextItemSelected(MenuItem item) {
1621         return false;
1622     }
1623 
1624     /**
1625      * When custom transitions are used with Fragments, the enter transition callback
1626      * is called when this Fragment is attached or detached when not popping the back stack.
1627      *
1628      * @param callback Used to manipulate the shared element transitions on this Fragment
1629      *                 when added not as a pop from the back stack.
1630      */
setEnterSharedElementCallback(SharedElementCallback callback)1631     public void setEnterSharedElementCallback(SharedElementCallback callback) {
1632         if (callback == null) {
1633             callback = SharedElementCallback.NULL_CALLBACK;
1634         }
1635         mEnterTransitionCallback = callback;
1636     }
1637 
1638     /**
1639      * @hide
1640      */
setEnterSharedElementTransitionCallback(SharedElementCallback callback)1641     public void setEnterSharedElementTransitionCallback(SharedElementCallback callback) {
1642         setEnterSharedElementCallback(callback);
1643     }
1644 
1645     /**
1646      * When custom transitions are used with Fragments, the exit transition callback
1647      * is called when this Fragment is attached or detached when popping the back stack.
1648      *
1649      * @param callback Used to manipulate the shared element transitions on this Fragment
1650      *                 when added as a pop from the back stack.
1651      */
setExitSharedElementCallback(SharedElementCallback callback)1652     public void setExitSharedElementCallback(SharedElementCallback callback) {
1653         if (callback == null) {
1654             callback = SharedElementCallback.NULL_CALLBACK;
1655         }
1656         mExitTransitionCallback = callback;
1657     }
1658 
1659     /**
1660      * @hide
1661      */
setExitSharedElementTransitionCallback(SharedElementCallback callback)1662     public void setExitSharedElementTransitionCallback(SharedElementCallback callback) {
1663         setExitSharedElementCallback(callback);
1664     }
1665 
1666     /**
1667      * Sets the Transition that will be used to move Views into the initial scene. The entering
1668      * Views will be those that are regular Views or ViewGroups that have
1669      * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
1670      * {@link android.transition.Visibility} as entering is governed by changing visibility from
1671      * {@link View#INVISIBLE} to {@link View#VISIBLE}. If <code>transition</code> is null,
1672      * entering Views will remain unaffected.
1673      *
1674      * @param transition The Transition to use to move Views into the initial Scene.
1675      * @attr ref android.R.styleable#Fragment_fragmentEnterTransition
1676      */
setEnterTransition(Transition transition)1677     public void setEnterTransition(Transition transition) {
1678         mEnterTransition = transition;
1679     }
1680 
1681     /**
1682      * Returns the Transition that will be used to move Views into the initial scene. The entering
1683      * Views will be those that are regular Views or ViewGroups that have
1684      * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
1685      * {@link android.transition.Visibility} as entering is governed by changing visibility from
1686      * {@link View#INVISIBLE} to {@link View#VISIBLE}.
1687      *
1688      * @return the Transition to use to move Views into the initial Scene.
1689      * @attr ref android.R.styleable#Fragment_fragmentEnterTransition
1690      */
getEnterTransition()1691     public Transition getEnterTransition() {
1692         return mEnterTransition;
1693     }
1694 
1695     /**
1696      * Sets the Transition that will be used to move Views out of the scene when the Fragment is
1697      * preparing to be removed, hidden, or detached because of popping the back stack. The exiting
1698      * Views will be those that are regular Views or ViewGroups that have
1699      * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
1700      * {@link android.transition.Visibility} as entering is governed by changing visibility from
1701      * {@link View#VISIBLE} to {@link View#INVISIBLE}. If <code>transition</code> is null,
1702      * entering Views will remain unaffected. If nothing is set, the default will be to
1703      * use the same value as set in {@link #setEnterTransition(android.transition.Transition)}.
1704      *
1705      * @param transition The Transition to use to move Views out of the Scene when the Fragment
1706      *                   is preparing to close.
1707      * @attr ref android.R.styleable#Fragment_fragmentExitTransition
1708      */
setReturnTransition(Transition transition)1709     public void setReturnTransition(Transition transition) {
1710         mReturnTransition = transition;
1711     }
1712 
1713     /**
1714      * Returns the Transition that will be used to move Views out of the scene when the Fragment is
1715      * preparing to be removed, hidden, or detached because of popping the back stack. The exiting
1716      * Views will be those that are regular Views or ViewGroups that have
1717      * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
1718      * {@link android.transition.Visibility} as entering is governed by changing visibility from
1719      * {@link View#VISIBLE} to {@link View#INVISIBLE}. If <code>transition</code> is null,
1720      * entering Views will remain unaffected.
1721      *
1722      * @return the Transition to use to move Views out of the Scene when the Fragment
1723      *         is preparing to close.
1724      * @attr ref android.R.styleable#Fragment_fragmentExitTransition
1725      */
getReturnTransition()1726     public Transition getReturnTransition() {
1727         return mReturnTransition == USE_DEFAULT_TRANSITION ? getEnterTransition()
1728                 : mReturnTransition;
1729     }
1730 
1731     /**
1732      * Sets the Transition that will be used to move Views out of the scene when the
1733      * fragment is removed, hidden, or detached when not popping the back stack.
1734      * The exiting Views will be those that are regular Views or ViewGroups that
1735      * have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
1736      * {@link android.transition.Visibility} as exiting is governed by changing visibility
1737      * from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null, the views will
1738      * remain unaffected.
1739      *
1740      * @param transition The Transition to use to move Views out of the Scene when the Fragment
1741      *                   is being closed not due to popping the back stack.
1742      * @attr ref android.R.styleable#Fragment_fragmentExitTransition
1743      */
setExitTransition(Transition transition)1744     public void setExitTransition(Transition transition) {
1745         mExitTransition = transition;
1746     }
1747 
1748     /**
1749      * Returns the Transition that will be used to move Views out of the scene when the
1750      * fragment is removed, hidden, or detached when not popping the back stack.
1751      * The exiting Views will be those that are regular Views or ViewGroups that
1752      * have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
1753      * {@link android.transition.Visibility} as exiting is governed by changing visibility
1754      * from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null, the views will
1755      * remain unaffected.
1756      *
1757      * @return the Transition to use to move Views out of the Scene when the Fragment
1758      *         is being closed not due to popping the back stack.
1759      * @attr ref android.R.styleable#Fragment_fragmentExitTransition
1760      */
getExitTransition()1761     public Transition getExitTransition() {
1762         return mExitTransition;
1763     }
1764 
1765     /**
1766      * Sets the Transition that will be used to move Views in to the scene when returning due
1767      * to popping a back stack. The entering Views will be those that are regular Views
1768      * or ViewGroups that have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions
1769      * will extend {@link android.transition.Visibility} as exiting is governed by changing
1770      * visibility from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null,
1771      * the views will remain unaffected. If nothing is set, the default will be to use the same
1772      * transition as {@link #setExitTransition(android.transition.Transition)}.
1773      *
1774      * @param transition The Transition to use to move Views into the scene when reentering from a
1775      *                   previously-started Activity.
1776      * @attr ref android.R.styleable#Fragment_fragmentReenterTransition
1777      */
setReenterTransition(Transition transition)1778     public void setReenterTransition(Transition transition) {
1779         mReenterTransition = transition;
1780     }
1781 
1782     /**
1783      * Returns the Transition that will be used to move Views in to the scene when returning due
1784      * to popping a back stack. The entering Views will be those that are regular Views
1785      * or ViewGroups that have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions
1786      * will extend {@link android.transition.Visibility} as exiting is governed by changing
1787      * visibility from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null,
1788      * the views will remain unaffected. If nothing is set, the default will be to use the same
1789      * transition as {@link #setExitTransition(android.transition.Transition)}.
1790      *
1791      * @return the Transition to use to move Views into the scene when reentering from a
1792      *                   previously-started Activity.
1793      * @attr ref android.R.styleable#Fragment_fragmentReenterTransition
1794      */
getReenterTransition()1795     public Transition getReenterTransition() {
1796         return mReenterTransition == USE_DEFAULT_TRANSITION ? getExitTransition()
1797                 : mReenterTransition;
1798     }
1799 
1800     /**
1801      * Sets the Transition that will be used for shared elements transferred into the content
1802      * Scene. Typical Transitions will affect size and location, such as
1803      * {@link android.transition.ChangeBounds}. A null
1804      * value will cause transferred shared elements to blink to the final position.
1805      *
1806      * @param transition The Transition to use for shared elements transferred into the content
1807      *                   Scene.
1808      * @attr ref android.R.styleable#Fragment_fragmentSharedElementEnterTransition
1809      */
setSharedElementEnterTransition(Transition transition)1810     public void setSharedElementEnterTransition(Transition transition) {
1811         mSharedElementEnterTransition = transition;
1812     }
1813 
1814     /**
1815      * Returns the Transition that will be used for shared elements transferred into the content
1816      * Scene. Typical Transitions will affect size and location, such as
1817      * {@link android.transition.ChangeBounds}. A null
1818      * value will cause transferred shared elements to blink to the final position.
1819      *
1820      * @return The Transition to use for shared elements transferred into the content
1821      *                   Scene.
1822      * @attr ref android.R.styleable#Fragment_fragmentSharedElementEnterTransition
1823      */
getSharedElementEnterTransition()1824     public Transition getSharedElementEnterTransition() {
1825         return mSharedElementEnterTransition;
1826     }
1827 
1828     /**
1829      * Sets the Transition that will be used for shared elements transferred back during a
1830      * pop of the back stack. This Transition acts in the leaving Fragment.
1831      * Typical Transitions will affect size and location, such as
1832      * {@link android.transition.ChangeBounds}. A null
1833      * value will cause transferred shared elements to blink to the final position.
1834      * If no value is set, the default will be to use the same value as
1835      * {@link #setSharedElementEnterTransition(android.transition.Transition)}.
1836      *
1837      * @param transition The Transition to use for shared elements transferred out of the content
1838      *                   Scene.
1839      * @attr ref android.R.styleable#Fragment_fragmentSharedElementReturnTransition
1840      */
setSharedElementReturnTransition(Transition transition)1841     public void setSharedElementReturnTransition(Transition transition) {
1842         mSharedElementReturnTransition = transition;
1843     }
1844 
1845     /**
1846      * Return the Transition that will be used for shared elements transferred back during a
1847      * pop of the back stack. This Transition acts in the leaving Fragment.
1848      * Typical Transitions will affect size and location, such as
1849      * {@link android.transition.ChangeBounds}. A null
1850      * value will cause transferred shared elements to blink to the final position.
1851      * If no value is set, the default will be to use the same value as
1852      * {@link #setSharedElementEnterTransition(android.transition.Transition)}.
1853      *
1854      * @return The Transition to use for shared elements transferred out of the content
1855      *                   Scene.
1856      * @attr ref android.R.styleable#Fragment_fragmentSharedElementReturnTransition
1857      */
getSharedElementReturnTransition()1858     public Transition getSharedElementReturnTransition() {
1859         return mSharedElementReturnTransition == USE_DEFAULT_TRANSITION ?
1860                 getSharedElementEnterTransition() : mSharedElementReturnTransition;
1861     }
1862 
1863     /**
1864      * Sets whether the the exit transition and enter transition overlap or not.
1865      * When true, the enter transition will start as soon as possible. When false, the
1866      * enter transition will wait until the exit transition completes before starting.
1867      *
1868      * @param allow true to start the enter transition when possible or false to
1869      *              wait until the exiting transition completes.
1870      * @attr ref android.R.styleable#Fragment_fragmentAllowEnterTransitionOverlap
1871      */
setAllowEnterTransitionOverlap(boolean allow)1872     public void setAllowEnterTransitionOverlap(boolean allow) {
1873         mAllowEnterTransitionOverlap = allow;
1874     }
1875 
1876     /**
1877      * Returns whether the the exit transition and enter transition overlap or not.
1878      * When true, the enter transition will start as soon as possible. When false, the
1879      * enter transition will wait until the exit transition completes before starting.
1880      *
1881      * @return true when the enter transition should start as soon as possible or false to
1882      * when it should wait until the exiting transition completes.
1883      * @attr ref android.R.styleable#Fragment_fragmentAllowEnterTransitionOverlap
1884      */
getAllowEnterTransitionOverlap()1885     public boolean getAllowEnterTransitionOverlap() {
1886         return (mAllowEnterTransitionOverlap == null) ? true : mAllowEnterTransitionOverlap;
1887     }
1888 
1889     /**
1890      * Sets whether the the return transition and reenter transition overlap or not.
1891      * When true, the reenter transition will start as soon as possible. When false, the
1892      * reenter transition will wait until the return transition completes before starting.
1893      *
1894      * @param allow true to start the reenter transition when possible or false to wait until the
1895      *              return transition completes.
1896      * @attr ref android.R.styleable#Fragment_fragmentAllowReturnTransitionOverlap
1897      */
setAllowReturnTransitionOverlap(boolean allow)1898     public void setAllowReturnTransitionOverlap(boolean allow) {
1899         mAllowReturnTransitionOverlap = allow;
1900     }
1901 
1902     /**
1903      * Returns whether the the return transition and reenter transition overlap or not.
1904      * When true, the reenter transition will start as soon as possible. When false, the
1905      * reenter transition will wait until the return transition completes before starting.
1906      *
1907      * @return true to start the reenter transition when possible or false to wait until the
1908      *         return transition completes.
1909      * @attr ref android.R.styleable#Fragment_fragmentAllowReturnTransitionOverlap
1910      */
getAllowReturnTransitionOverlap()1911     public boolean getAllowReturnTransitionOverlap() {
1912         return (mAllowReturnTransitionOverlap == null) ? true : mAllowReturnTransitionOverlap;
1913     }
1914 
1915     /**
1916      * Print the Fragments's state into the given stream.
1917      *
1918      * @param prefix Text to print at the front of each line.
1919      * @param fd The raw file descriptor that the dump is being sent to.
1920      * @param writer The PrintWriter to which you should dump your state.  This will be
1921      * closed for you after you return.
1922      * @param args additional arguments to the dump request.
1923      */
dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args)1924     public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
1925         writer.print(prefix); writer.print("mFragmentId=#");
1926         writer.print(Integer.toHexString(mFragmentId));
1927         writer.print(" mContainerId=#");
1928         writer.print(Integer.toHexString(mContainerId));
1929         writer.print(" mTag="); writer.println(mTag);
1930         writer.print(prefix); writer.print("mState="); writer.print(mState);
1931         writer.print(" mIndex="); writer.print(mIndex);
1932         writer.print(" mWho="); writer.print(mWho);
1933         writer.print(" mBackStackNesting="); writer.println(mBackStackNesting);
1934         writer.print(prefix); writer.print("mAdded="); writer.print(mAdded);
1935         writer.print(" mRemoving="); writer.print(mRemoving);
1936         writer.print(" mResumed="); writer.print(mResumed);
1937         writer.print(" mFromLayout="); writer.print(mFromLayout);
1938         writer.print(" mInLayout="); writer.println(mInLayout);
1939         writer.print(prefix); writer.print("mHidden="); writer.print(mHidden);
1940         writer.print(" mDetached="); writer.print(mDetached);
1941         writer.print(" mMenuVisible="); writer.print(mMenuVisible);
1942         writer.print(" mHasMenu="); writer.println(mHasMenu);
1943         writer.print(prefix); writer.print("mRetainInstance="); writer.print(mRetainInstance);
1944         writer.print(" mRetaining="); writer.print(mRetaining);
1945         writer.print(" mUserVisibleHint="); writer.println(mUserVisibleHint);
1946         if (mFragmentManager != null) {
1947             writer.print(prefix); writer.print("mFragmentManager=");
1948             writer.println(mFragmentManager);
1949         }
1950         if (mActivity != null) {
1951             writer.print(prefix); writer.print("mActivity=");
1952             writer.println(mActivity);
1953         }
1954         if (mParentFragment != null) {
1955             writer.print(prefix); writer.print("mParentFragment=");
1956             writer.println(mParentFragment);
1957         }
1958         if (mArguments != null) {
1959             writer.print(prefix); writer.print("mArguments="); writer.println(mArguments);
1960         }
1961         if (mSavedFragmentState != null) {
1962             writer.print(prefix); writer.print("mSavedFragmentState=");
1963             writer.println(mSavedFragmentState);
1964         }
1965         if (mSavedViewState != null) {
1966             writer.print(prefix); writer.print("mSavedViewState=");
1967             writer.println(mSavedViewState);
1968         }
1969         if (mTarget != null) {
1970             writer.print(prefix); writer.print("mTarget="); writer.print(mTarget);
1971             writer.print(" mTargetRequestCode=");
1972             writer.println(mTargetRequestCode);
1973         }
1974         if (mNextAnim != 0) {
1975             writer.print(prefix); writer.print("mNextAnim="); writer.println(mNextAnim);
1976         }
1977         if (mContainer != null) {
1978             writer.print(prefix); writer.print("mContainer="); writer.println(mContainer);
1979         }
1980         if (mView != null) {
1981             writer.print(prefix); writer.print("mView="); writer.println(mView);
1982         }
1983         if (mAnimatingAway != null) {
1984             writer.print(prefix); writer.print("mAnimatingAway="); writer.println(mAnimatingAway);
1985             writer.print(prefix); writer.print("mStateAfterAnimating=");
1986             writer.println(mStateAfterAnimating);
1987         }
1988         if (mLoaderManager != null) {
1989             writer.print(prefix); writer.println("Loader Manager:");
1990             mLoaderManager.dump(prefix + "  ", fd, writer, args);
1991         }
1992         if (mChildFragmentManager != null) {
1993             writer.print(prefix); writer.println("Child " + mChildFragmentManager + ":");
1994             mChildFragmentManager.dump(prefix + "  ", fd, writer, args);
1995         }
1996     }
1997 
findFragmentByWho(String who)1998     Fragment findFragmentByWho(String who) {
1999         if (who.equals(mWho)) {
2000             return this;
2001         }
2002         if (mChildFragmentManager != null) {
2003             return mChildFragmentManager.findFragmentByWho(who);
2004         }
2005         return null;
2006     }
2007 
instantiateChildFragmentManager()2008     void instantiateChildFragmentManager() {
2009         mChildFragmentManager = new FragmentManagerImpl();
2010         mChildFragmentManager.attachActivity(mActivity, new FragmentContainer() {
2011             @Override
2012             public View findViewById(int id) {
2013                 if (mView == null) {
2014                     throw new IllegalStateException("Fragment does not have a view");
2015                 }
2016                 return mView.findViewById(id);
2017             }
2018 
2019             @Override
2020             public boolean hasView() {
2021                 return (mView != null);
2022             }
2023         }, this);
2024     }
2025 
performCreate(Bundle savedInstanceState)2026     void performCreate(Bundle savedInstanceState) {
2027         if (mChildFragmentManager != null) {
2028             mChildFragmentManager.noteStateNotSaved();
2029         }
2030         mCalled = false;
2031         onCreate(savedInstanceState);
2032         if (!mCalled) {
2033             throw new SuperNotCalledException("Fragment " + this
2034                     + " did not call through to super.onCreate()");
2035         }
2036         if (savedInstanceState != null) {
2037             Parcelable p = savedInstanceState.getParcelable(Activity.FRAGMENTS_TAG);
2038             if (p != null) {
2039                 if (mChildFragmentManager == null) {
2040                     instantiateChildFragmentManager();
2041                 }
2042                 mChildFragmentManager.restoreAllState(p, null);
2043                 mChildFragmentManager.dispatchCreate();
2044             }
2045         }
2046     }
2047 
performCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)2048     View performCreateView(LayoutInflater inflater, ViewGroup container,
2049             Bundle savedInstanceState) {
2050         if (mChildFragmentManager != null) {
2051             mChildFragmentManager.noteStateNotSaved();
2052         }
2053         return onCreateView(inflater, container, savedInstanceState);
2054     }
2055 
performActivityCreated(Bundle savedInstanceState)2056     void performActivityCreated(Bundle savedInstanceState) {
2057         if (mChildFragmentManager != null) {
2058             mChildFragmentManager.noteStateNotSaved();
2059         }
2060         mCalled = false;
2061         onActivityCreated(savedInstanceState);
2062         if (!mCalled) {
2063             throw new SuperNotCalledException("Fragment " + this
2064                     + " did not call through to super.onActivityCreated()");
2065         }
2066         if (mChildFragmentManager != null) {
2067             mChildFragmentManager.dispatchActivityCreated();
2068         }
2069     }
2070 
performStart()2071     void performStart() {
2072         if (mChildFragmentManager != null) {
2073             mChildFragmentManager.noteStateNotSaved();
2074             mChildFragmentManager.execPendingActions();
2075         }
2076         mCalled = false;
2077         onStart();
2078         if (!mCalled) {
2079             throw new SuperNotCalledException("Fragment " + this
2080                     + " did not call through to super.onStart()");
2081         }
2082         if (mChildFragmentManager != null) {
2083             mChildFragmentManager.dispatchStart();
2084         }
2085         if (mLoaderManager != null) {
2086             mLoaderManager.doReportStart();
2087         }
2088     }
2089 
performResume()2090     void performResume() {
2091         if (mChildFragmentManager != null) {
2092             mChildFragmentManager.noteStateNotSaved();
2093             mChildFragmentManager.execPendingActions();
2094         }
2095         mCalled = false;
2096         onResume();
2097         if (!mCalled) {
2098             throw new SuperNotCalledException("Fragment " + this
2099                     + " did not call through to super.onResume()");
2100         }
2101         if (mChildFragmentManager != null) {
2102             mChildFragmentManager.dispatchResume();
2103             mChildFragmentManager.execPendingActions();
2104         }
2105     }
2106 
performConfigurationChanged(Configuration newConfig)2107     void performConfigurationChanged(Configuration newConfig) {
2108         onConfigurationChanged(newConfig);
2109         if (mChildFragmentManager != null) {
2110             mChildFragmentManager.dispatchConfigurationChanged(newConfig);
2111         }
2112     }
2113 
performLowMemory()2114     void performLowMemory() {
2115         onLowMemory();
2116         if (mChildFragmentManager != null) {
2117             mChildFragmentManager.dispatchLowMemory();
2118         }
2119     }
2120 
performTrimMemory(int level)2121     void performTrimMemory(int level) {
2122         onTrimMemory(level);
2123         if (mChildFragmentManager != null) {
2124             mChildFragmentManager.dispatchTrimMemory(level);
2125         }
2126     }
2127 
performCreateOptionsMenu(Menu menu, MenuInflater inflater)2128     boolean performCreateOptionsMenu(Menu menu, MenuInflater inflater) {
2129         boolean show = false;
2130         if (!mHidden) {
2131             if (mHasMenu && mMenuVisible) {
2132                 show = true;
2133                 onCreateOptionsMenu(menu, inflater);
2134             }
2135             if (mChildFragmentManager != null) {
2136                 show |= mChildFragmentManager.dispatchCreateOptionsMenu(menu, inflater);
2137             }
2138         }
2139         return show;
2140     }
2141 
performPrepareOptionsMenu(Menu menu)2142     boolean performPrepareOptionsMenu(Menu menu) {
2143         boolean show = false;
2144         if (!mHidden) {
2145             if (mHasMenu && mMenuVisible) {
2146                 show = true;
2147                 onPrepareOptionsMenu(menu);
2148             }
2149             if (mChildFragmentManager != null) {
2150                 show |= mChildFragmentManager.dispatchPrepareOptionsMenu(menu);
2151             }
2152         }
2153         return show;
2154     }
2155 
performOptionsItemSelected(MenuItem item)2156     boolean performOptionsItemSelected(MenuItem item) {
2157         if (!mHidden) {
2158             if (mHasMenu && mMenuVisible) {
2159                 if (onOptionsItemSelected(item)) {
2160                     return true;
2161                 }
2162             }
2163             if (mChildFragmentManager != null) {
2164                 if (mChildFragmentManager.dispatchOptionsItemSelected(item)) {
2165                     return true;
2166                 }
2167             }
2168         }
2169         return false;
2170     }
2171 
performContextItemSelected(MenuItem item)2172     boolean performContextItemSelected(MenuItem item) {
2173         if (!mHidden) {
2174             if (onContextItemSelected(item)) {
2175                 return true;
2176             }
2177             if (mChildFragmentManager != null) {
2178                 if (mChildFragmentManager.dispatchContextItemSelected(item)) {
2179                     return true;
2180                 }
2181             }
2182         }
2183         return false;
2184     }
2185 
performOptionsMenuClosed(Menu menu)2186     void performOptionsMenuClosed(Menu menu) {
2187         if (!mHidden) {
2188             if (mHasMenu && mMenuVisible) {
2189                 onOptionsMenuClosed(menu);
2190             }
2191             if (mChildFragmentManager != null) {
2192                 mChildFragmentManager.dispatchOptionsMenuClosed(menu);
2193             }
2194         }
2195     }
2196 
performSaveInstanceState(Bundle outState)2197     void performSaveInstanceState(Bundle outState) {
2198         onSaveInstanceState(outState);
2199         if (mChildFragmentManager != null) {
2200             Parcelable p = mChildFragmentManager.saveAllState();
2201             if (p != null) {
2202                 outState.putParcelable(Activity.FRAGMENTS_TAG, p);
2203             }
2204         }
2205     }
2206 
performPause()2207     void performPause() {
2208         if (mChildFragmentManager != null) {
2209             mChildFragmentManager.dispatchPause();
2210         }
2211         mCalled = false;
2212         onPause();
2213         if (!mCalled) {
2214             throw new SuperNotCalledException("Fragment " + this
2215                     + " did not call through to super.onPause()");
2216         }
2217     }
2218 
performStop()2219     void performStop() {
2220         if (mChildFragmentManager != null) {
2221             mChildFragmentManager.dispatchStop();
2222         }
2223         mCalled = false;
2224         onStop();
2225         if (!mCalled) {
2226             throw new SuperNotCalledException("Fragment " + this
2227                     + " did not call through to super.onStop()");
2228         }
2229 
2230         if (mLoadersStarted) {
2231             mLoadersStarted = false;
2232             if (!mCheckedForLoaderManager) {
2233                 mCheckedForLoaderManager = true;
2234                 mLoaderManager = mActivity.getLoaderManager(mWho, mLoadersStarted, false);
2235             }
2236             if (mLoaderManager != null) {
2237                 if (mActivity == null || !mActivity.mChangingConfigurations) {
2238                     mLoaderManager.doStop();
2239                 } else {
2240                     mLoaderManager.doRetain();
2241                 }
2242             }
2243         }
2244     }
2245 
performDestroyView()2246     void performDestroyView() {
2247         if (mChildFragmentManager != null) {
2248             mChildFragmentManager.dispatchDestroyView();
2249         }
2250         mCalled = false;
2251         onDestroyView();
2252         if (!mCalled) {
2253             throw new SuperNotCalledException("Fragment " + this
2254                     + " did not call through to super.onDestroyView()");
2255         }
2256         if (mLoaderManager != null) {
2257             mLoaderManager.doReportNextStart();
2258         }
2259     }
2260 
performDestroy()2261     void performDestroy() {
2262         if (mChildFragmentManager != null) {
2263             mChildFragmentManager.dispatchDestroy();
2264         }
2265         mCalled = false;
2266         onDestroy();
2267         if (!mCalled) {
2268             throw new SuperNotCalledException("Fragment " + this
2269                     + " did not call through to super.onDestroy()");
2270         }
2271     }
2272 
loadTransition(Context context, TypedArray typedArray, Transition currentValue, Transition defaultValue, int id)2273     private static Transition loadTransition(Context context, TypedArray typedArray,
2274             Transition currentValue, Transition defaultValue, int id) {
2275         if (currentValue != defaultValue) {
2276             return currentValue;
2277         }
2278         int transitionId = typedArray.getResourceId(id, 0);
2279         Transition transition = defaultValue;
2280         if (transitionId != 0 && transitionId != com.android.internal.R.transition.no_transition) {
2281             TransitionInflater inflater = TransitionInflater.from(context);
2282             transition = inflater.inflateTransition(transitionId);
2283             if (transition instanceof TransitionSet &&
2284                     ((TransitionSet)transition).getTransitionCount() == 0) {
2285                 transition = null;
2286             }
2287         }
2288         return transition;
2289     }
2290 
2291 }
2292