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.CallSuper;
21 import android.annotation.NonNull;
22 import android.annotation.Nullable;
23 import android.annotation.StringRes;
24 import android.compat.annotation.UnsupportedAppUsage;
25 import android.content.ComponentCallbacks2;
26 import android.content.Context;
27 import android.content.Intent;
28 import android.content.IntentSender;
29 import android.content.res.Configuration;
30 import android.content.res.Resources;
31 import android.content.res.TypedArray;
32 import android.os.Build;
33 import android.os.Build.VERSION_CODES;
34 import android.os.Bundle;
35 import android.os.Looper;
36 import android.os.Parcel;
37 import android.os.Parcelable;
38 import android.os.UserHandle;
39 import android.transition.Transition;
40 import android.transition.TransitionInflater;
41 import android.transition.TransitionSet;
42 import android.util.AndroidRuntimeException;
43 import android.util.ArrayMap;
44 import android.util.AttributeSet;
45 import android.util.DebugUtils;
46 import android.util.SparseArray;
47 import android.util.SuperNotCalledException;
48 import android.view.ContextMenu;
49 import android.view.ContextMenu.ContextMenuInfo;
50 import android.view.LayoutInflater;
51 import android.view.Menu;
52 import android.view.MenuInflater;
53 import android.view.MenuItem;
54 import android.view.View;
55 import android.view.View.OnCreateContextMenuListener;
56 import android.view.ViewGroup;
57 import android.widget.AdapterView;
58 
59 import java.io.FileDescriptor;
60 import java.io.PrintWriter;
61 import java.lang.reflect.InvocationTargetException;
62 
63 /**
64  * A Fragment is a piece of an application's user interface or behavior
65  * that can be placed in an {@link Activity}.  Interaction with fragments
66  * is done through {@link FragmentManager}, which can be obtained via
67  * {@link Activity#getFragmentManager() Activity.getFragmentManager()} and
68  * {@link Fragment#getFragmentManager() Fragment.getFragmentManager()}.
69  *
70  * <p>The Fragment class can be used many ways to achieve a wide variety of
71  * results. In its core, it represents a particular operation or interface
72  * that is running within a larger {@link Activity}.  A Fragment is closely
73  * tied to the Activity it is in, and can not be used apart from one.  Though
74  * Fragment defines its own lifecycle, that lifecycle is dependent on its
75  * activity: if the activity is stopped, no fragments inside of it can be
76  * started; when the activity is destroyed, all fragments will be destroyed.
77  *
78  * <p>All subclasses of Fragment must include a public no-argument constructor.
79  * The framework will often re-instantiate a fragment class when needed,
80  * in particular during state restore, and needs to be able to find this
81  * constructor to instantiate it.  If the no-argument constructor is not
82  * available, a runtime exception will occur in some cases during state
83  * restore.
84  *
85  * <p>Topics covered here:
86  * <ol>
87  * <li><a href="#OlderPlatforms">Older Platforms</a>
88  * <li><a href="#Lifecycle">Lifecycle</a>
89  * <li><a href="#Layout">Layout</a>
90  * <li><a href="#BackStack">Back Stack</a>
91  * </ol>
92  *
93  * <div class="special reference">
94  * <h3>Developer Guides</h3>
95  * <p>For more information about using fragments, read the
96  * <a href="{@docRoot}guide/components/fragments.html">Fragments</a> developer guide.</p>
97  * </div>
98  *
99  * <a name="OlderPlatforms"></a>
100  * <h3>Older Platforms</h3>
101  *
102  * While the Fragment API was introduced in
103  * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, a version of the API
104  * at is also available for use on older platforms through
105  * {@link android.support.v4.app.FragmentActivity}.  See the blog post
106  * <a href="http://android-developers.blogspot.com/2011/03/fragments-for-all.html">
107  * Fragments For All</a> for more details.
108  *
109  * <a name="Lifecycle"></a>
110  * <h3>Lifecycle</h3>
111  *
112  * <p>Though a Fragment's lifecycle is tied to its owning activity, it has
113  * its own wrinkle on the standard activity lifecycle.  It includes basic
114  * activity lifecycle methods such as {@link #onResume}, but also important
115  * are methods related to interactions with the activity and UI generation.
116  *
117  * <p>The core series of lifecycle methods that are called to bring a fragment
118  * up to resumed state (interacting with the user) are:
119  *
120  * <ol>
121  * <li> {@link #onAttach} called once the fragment is associated with its activity.
122  * <li> {@link #onCreate} called to do initial creation of the fragment.
123  * <li> {@link #onCreateView} creates and returns the view hierarchy associated
124  * with the fragment.
125  * <li> {@link #onActivityCreated} tells the fragment that its activity has
126  * completed its own {@link Activity#onCreate Activity.onCreate()}.
127  * <li> {@link #onViewStateRestored} tells the fragment that all of the saved
128  * state of its view hierarchy has been restored.
129  * <li> {@link #onStart} makes the fragment visible to the user (based on its
130  * containing activity being started).
131  * <li> {@link #onResume} makes the fragment begin interacting with the user
132  * (based on its containing activity being resumed).
133  * </ol>
134  *
135  * <p>As a fragment is no longer being used, it goes through a reverse
136  * series of callbacks:
137  *
138  * <ol>
139  * <li> {@link #onPause} fragment is no longer interacting with the user either
140  * because its activity is being paused or a fragment operation is modifying it
141  * in the activity.
142  * <li> {@link #onStop} fragment is no longer visible to the user either
143  * because its activity is being stopped or a fragment operation is modifying it
144  * in the activity.
145  * <li> {@link #onDestroyView} allows the fragment to clean up resources
146  * associated with its View.
147  * <li> {@link #onDestroy} called to do final cleanup of the fragment's state.
148  * <li> {@link #onDetach} called immediately prior to the fragment no longer
149  * being associated with its activity.
150  * </ol>
151  *
152  * <a name="Layout"></a>
153  * <h3>Layout</h3>
154  *
155  * <p>Fragments can be used as part of your application's layout, allowing
156  * you to better modularize your code and more easily adjust your user
157  * interface to the screen it is running on.  As an example, we can look
158  * at a simple program consisting of a list of items, and display of the
159  * details of each item.</p>
160  *
161  * <p>An activity's layout XML can include <code>&lt;fragment&gt;</code> tags
162  * to embed fragment instances inside of the layout.  For example, here is
163  * a simple layout that embeds one fragment:</p>
164  *
165  * {@sample development/samples/ApiDemos/res/layout/fragment_layout.xml layout}
166  *
167  * <p>The layout is installed in the activity in the normal way:</p>
168  *
169  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
170  *      main}
171  *
172  * <p>The titles fragment, showing a list of titles, is fairly simple, relying
173  * on {@link ListFragment} for most of its work.  Note the implementation of
174  * clicking an item: depending on the current activity's layout, it can either
175  * create and display a new fragment to show the details in-place (more about
176  * this later), or start a new activity to show the details.</p>
177  *
178  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
179  *      titles}
180  *
181  * <p>The details fragment showing the contents of a selected item just
182  * displays a string of text based on an index of a string array built in to
183  * the app:</p>
184  *
185  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
186  *      details}
187  *
188  * <p>In this case when the user clicks on a title, there is no details
189  * container in the current activity, so the titles fragment's click code will
190  * launch a new activity to display the details fragment:</p>
191  *
192  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
193  *      details_activity}
194  *
195  * <p>However the screen may be large enough to show both the list of titles
196  * and details about the currently selected title.  To use such a layout on
197  * a landscape screen, this alternative layout can be placed under layout-land:</p>
198  *
199  * {@sample development/samples/ApiDemos/res/layout-land/fragment_layout.xml layout}
200  *
201  * <p>Note how the prior code will adjust to this alternative UI flow: the titles
202  * fragment will now embed the details fragment inside of this activity, and the
203  * details activity will finish itself if it is running in a configuration
204  * where the details can be shown in-place.
205  *
206  * <p>When a configuration change causes the activity hosting these fragments
207  * to restart, its new instance may use a different layout that doesn't
208  * include the same fragments as the previous layout.  In this case all of
209  * the previous fragments will still be instantiated and running in the new
210  * instance.  However, any that are no longer associated with a &lt;fragment&gt;
211  * tag in the view hierarchy will not have their content view created
212  * and will return false from {@link #isInLayout}.  (The code here also shows
213  * how you can determine if a fragment placed in a container is no longer
214  * running in a layout with that container and avoid creating its view hierarchy
215  * in that case.)
216  *
217  * <p>The attributes of the &lt;fragment&gt; tag are used to control the
218  * LayoutParams provided when attaching the fragment's view to the parent
219  * container.  They can also be parsed by the fragment in {@link #onInflate}
220  * as parameters.
221  *
222  * <p>The fragment being instantiated must have some kind of unique identifier
223  * so that it can be re-associated with a previous instance if the parent
224  * activity needs to be destroyed and recreated.  This can be provided these
225  * ways:
226  *
227  * <ul>
228  * <li>If nothing is explicitly supplied, the view ID of the container will
229  * be used.
230  * <li><code>android:tag</code> can be used in &lt;fragment&gt; to provide
231  * a specific tag name for the fragment.
232  * <li><code>android:id</code> can be used in &lt;fragment&gt; to provide
233  * a specific identifier for the fragment.
234  * </ul>
235  *
236  * <a name="BackStack"></a>
237  * <h3>Back Stack</h3>
238  *
239  * <p>The transaction in which fragments are modified can be placed on an
240  * internal back-stack of the owning activity.  When the user presses back
241  * in the activity, any transactions on the back stack are popped off before
242  * the activity itself is finished.
243  *
244  * <p>For example, consider this simple fragment that is instantiated with
245  * an integer argument and displays that in a TextView in its UI:</p>
246  *
247  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentStack.java
248  *      fragment}
249  *
250  * <p>A function that creates a new instance of the fragment, replacing
251  * whatever current fragment instance is being shown and pushing that change
252  * on to the back stack could be written as:
253  *
254  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentStack.java
255  *      add_stack}
256  *
257  * <p>After each call to this function, a new entry is on the stack, and
258  * pressing back will pop it to return the user to whatever previous state
259  * the activity UI was in.
260  *
261  * @deprecated Use the <a href="{@docRoot}tools/extras/support-library.html">Support Library</a>
262  *      {@link android.support.v4.app.Fragment} for consistent behavior across all devices
263  *      and access to <a href="{@docRoot}topic/libraries/architecture/lifecycle.html">Lifecycle</a>.
264  */
265 @Deprecated
266 public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListener {
267     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
268     private static final ArrayMap<String, Class<?>> sClassMap =
269             new ArrayMap<String, Class<?>>();
270 
271     static final int INVALID_STATE = -1;   // Invalid state used as a null value.
272     static final int INITIALIZING = 0;     // Not yet created.
273     static final int CREATED = 1;          // Created.
274     static final int ACTIVITY_CREATED = 2; // The activity has finished its creation.
275     static final int STOPPED = 3;          // Fully created, not started.
276     static final int STARTED = 4;          // Created and started, not resumed.
277     static final int RESUMED = 5;          // Created started and resumed.
278 
279     private static final Transition USE_DEFAULT_TRANSITION = new TransitionSet();
280 
281     int mState = INITIALIZING;
282 
283     // When instantiated from saved state, this is the saved state.
284     @UnsupportedAppUsage
285     Bundle mSavedFragmentState;
286     SparseArray<Parcelable> mSavedViewState;
287 
288     // Index into active fragment array.
289     @UnsupportedAppUsage
290     int mIndex = -1;
291 
292     // Internal unique name for this fragment;
293     @UnsupportedAppUsage
294     String mWho;
295 
296     // Construction arguments;
297     Bundle mArguments;
298 
299     // Target fragment.
300     Fragment mTarget;
301 
302     // For use when retaining a fragment: this is the index of the last mTarget.
303     int mTargetIndex = -1;
304 
305     // Target request code.
306     int mTargetRequestCode;
307 
308     // True if the fragment is in the list of added fragments.
309     @UnsupportedAppUsage
310     boolean mAdded;
311 
312     // If set this fragment is being removed from its activity.
313     boolean mRemoving;
314 
315     // Set to true if this fragment was instantiated from a layout file.
316     boolean mFromLayout;
317 
318     // Set to true when the view has actually been inflated in its layout.
319     boolean mInLayout;
320 
321     // True if this fragment has been restored from previously saved state.
322     boolean mRestored;
323 
324     // True if performCreateView has been called and a matching call to performDestroyView
325     // has not yet happened.
326     boolean mPerformedCreateView;
327 
328     // Number of active back stack entries this fragment is in.
329     int mBackStackNesting;
330 
331     // The fragment manager we are associated with.  Set as soon as the
332     // fragment is used in a transaction; cleared after it has been removed
333     // from all transactions.
334     @UnsupportedAppUsage
335     FragmentManagerImpl mFragmentManager;
336 
337     // Activity this fragment is attached to.
338     @UnsupportedAppUsage
339     FragmentHostCallback mHost;
340 
341     // Private fragment manager for child fragments inside of this one.
342     @UnsupportedAppUsage
343     FragmentManagerImpl mChildFragmentManager;
344 
345     // For use when restoring fragment state and descendant fragments are retained.
346     // This state is set by FragmentState.instantiate and cleared in onCreate.
347     FragmentManagerNonConfig mChildNonConfig;
348 
349     // If this Fragment is contained in another Fragment, this is that container.
350     Fragment mParentFragment;
351 
352     // The optional identifier for this fragment -- either the container ID if it
353     // was dynamically added to the view hierarchy, or the ID supplied in
354     // layout.
355     @UnsupportedAppUsage
356     int mFragmentId;
357 
358     // When a fragment is being dynamically added to the view hierarchy, this
359     // is the identifier of the parent container it is being added to.
360     int mContainerId;
361 
362     // The optional named tag for this fragment -- usually used to find
363     // fragments that are not part of the layout.
364     String mTag;
365 
366     // Set to true when the app has requested that this fragment be hidden
367     // from the user.
368     boolean mHidden;
369 
370     // Set to true when the app has requested that this fragment be detached.
371     boolean mDetached;
372 
373     // If set this fragment would like its instance retained across
374     // configuration changes.
375     boolean mRetainInstance;
376 
377     // If set this fragment is being retained across the current config change.
378     boolean mRetaining;
379 
380     // If set this fragment has menu items to contribute.
381     boolean mHasMenu;
382 
383     // Set to true to allow the fragment's menu to be shown.
384     boolean mMenuVisible = true;
385 
386     // Used to verify that subclasses call through to super class.
387     boolean mCalled;
388 
389     // The parent container of the fragment after dynamically added to UI.
390     ViewGroup mContainer;
391 
392     // The View generated for this fragment.
393     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
394     View mView;
395 
396     // Whether this fragment should defer starting until after other fragments
397     // have been started and their loaders are finished.
398     boolean mDeferStart;
399 
400     // Hint provided by the app that this fragment is currently visible to the user.
401     boolean mUserVisibleHint = true;
402 
403     LoaderManagerImpl mLoaderManager;
404     @UnsupportedAppUsage
405     boolean mLoadersStarted;
406     boolean mCheckedForLoaderManager;
407 
408     // The animation and transition information for the fragment. This will be null
409     // unless the elements are explicitly accessed and should remain null for Fragments
410     // without Views.
411     AnimationInfo mAnimationInfo;
412 
413     // True if the View was added, and its animation has yet to be run. This could
414     // also indicate that the fragment view hasn't been made visible, even if there is no
415     // animation for this fragment.
416     boolean mIsNewlyAdded;
417 
418     // True if mHidden has been changed and the animation should be scheduled.
419     boolean mHiddenChanged;
420 
421     // The cached value from onGetLayoutInflater(Bundle) that will be returned from
422     // getLayoutInflater()
423     LayoutInflater mLayoutInflater;
424 
425     // Keep track of whether or not this Fragment has run performCreate(). Retained instance
426     // fragments can have mRetaining set to true without going through creation, so we must
427     // track it separately.
428     boolean mIsCreated;
429 
430     /**
431      * State information that has been retrieved from a fragment instance
432      * through {@link FragmentManager#saveFragmentInstanceState(Fragment)
433      * FragmentManager.saveFragmentInstanceState}.
434      *
435      * @deprecated Use {@link android.support.v4.app.Fragment.SavedState}
436      */
437     @Deprecated
438     public static class SavedState implements Parcelable {
439         final Bundle mState;
440 
SavedState(Bundle state)441         SavedState(Bundle state) {
442             mState = state;
443         }
444 
SavedState(Parcel in, ClassLoader loader)445         SavedState(Parcel in, ClassLoader loader) {
446             mState = in.readBundle();
447             if (loader != null && mState != null) {
448                 mState.setClassLoader(loader);
449             }
450         }
451 
452         @Override
describeContents()453         public int describeContents() {
454             return 0;
455         }
456 
457         @Override
writeToParcel(Parcel dest, int flags)458         public void writeToParcel(Parcel dest, int flags) {
459             dest.writeBundle(mState);
460         }
461 
462         public static final Parcelable.ClassLoaderCreator<SavedState> CREATOR
463                 = new Parcelable.ClassLoaderCreator<SavedState>() {
464             public SavedState createFromParcel(Parcel in) {
465                 return new SavedState(in, null);
466             }
467 
468             public SavedState createFromParcel(Parcel in, ClassLoader loader) {
469                 return new SavedState(in, loader);
470             }
471 
472             public SavedState[] newArray(int size) {
473                 return new SavedState[size];
474             }
475         };
476     }
477 
478     /**
479      * Thrown by {@link Fragment#instantiate(Context, String, Bundle)} when
480      * there is an instantiation failure.
481      *
482      * @deprecated Use {@link android.support.v4.app.Fragment.InstantiationException}
483      */
484     @Deprecated
485     static public class InstantiationException extends AndroidRuntimeException {
InstantiationException(String msg, Exception cause)486         public InstantiationException(String msg, Exception cause) {
487             super(msg, cause);
488         }
489     }
490 
491     /**
492      * Default constructor.  <strong>Every</strong> fragment must have an
493      * empty constructor, so it can be instantiated when restoring its
494      * activity's state.  It is strongly recommended that subclasses do not
495      * have other constructors with parameters, since these constructors
496      * will not be called when the fragment is re-instantiated; instead,
497      * arguments can be supplied by the caller with {@link #setArguments}
498      * and later retrieved by the Fragment with {@link #getArguments}.
499      *
500      * <p>Applications should generally not implement a constructor. Prefer
501      * {@link #onAttach(Context)} instead. It is the first place application code can run where
502      * the fragment is ready to be used - the point where the fragment is actually associated with
503      * its context. Some applications may also want to implement {@link #onInflate} to retrieve
504      * attributes from a layout resource, although note this happens when the fragment is attached.
505      */
Fragment()506     public Fragment() {
507     }
508 
509     /**
510      * Like {@link #instantiate(Context, String, Bundle)} but with a null
511      * argument Bundle.
512      */
instantiate(Context context, String fname)513     public static Fragment instantiate(Context context, String fname) {
514         return instantiate(context, fname, null);
515     }
516 
517     /**
518      * Create a new instance of a Fragment with the given class name.  This is
519      * the same as calling its empty constructor.
520      *
521      * @param context The calling context being used to instantiate the fragment.
522      * This is currently just used to get its ClassLoader.
523      * @param fname The class name of the fragment to instantiate.
524      * @param args Bundle of arguments to supply to the fragment, which it
525      * can retrieve with {@link #getArguments()}.  May be null.
526      * @return Returns a new fragment instance.
527      * @throws InstantiationException If there is a failure in instantiating
528      * the given fragment class.  This is a runtime exception; it is not
529      * normally expected to happen.
530      */
instantiate(Context context, String fname, @Nullable Bundle args)531     public static Fragment instantiate(Context context, String fname, @Nullable Bundle args) {
532         try {
533             Class<?> clazz = sClassMap.get(fname);
534             if (clazz == null) {
535                 // Class not found in the cache, see if it's real, and try to add it
536                 clazz = context.getClassLoader().loadClass(fname);
537                 if (!Fragment.class.isAssignableFrom(clazz)) {
538                     throw new InstantiationException("Trying to instantiate a class " + fname
539                             + " that is not a Fragment", new ClassCastException());
540                 }
541                 sClassMap.put(fname, clazz);
542             }
543             Fragment f = (Fragment) clazz.getConstructor().newInstance();
544             if (args != null) {
545                 args.setClassLoader(f.getClass().getClassLoader());
546                 f.setArguments(args);
547             }
548             return f;
549         } catch (ClassNotFoundException e) {
550             throw new InstantiationException("Unable to instantiate fragment " + fname
551                     + ": make sure class name exists, is public, and has an"
552                     + " empty constructor that is public", e);
553         } catch (java.lang.InstantiationException e) {
554             throw new InstantiationException("Unable to instantiate fragment " + fname
555                     + ": make sure class name exists, is public, and has an"
556                     + " empty constructor that is public", e);
557         } catch (IllegalAccessException e) {
558             throw new InstantiationException("Unable to instantiate fragment " + fname
559                     + ": make sure class name exists, is public, and has an"
560                     + " empty constructor that is public", e);
561         } catch (NoSuchMethodException e) {
562             throw new InstantiationException("Unable to instantiate fragment " + fname
563                     + ": could not find Fragment constructor", e);
564         } catch (InvocationTargetException e) {
565             throw new InstantiationException("Unable to instantiate fragment " + fname
566                     + ": calling Fragment constructor caused an exception", e);
567         }
568     }
569 
restoreViewState(Bundle savedInstanceState)570     final void restoreViewState(Bundle savedInstanceState) {
571         if (mSavedViewState != null) {
572             mView.restoreHierarchyState(mSavedViewState);
573             mSavedViewState = null;
574         }
575         mCalled = false;
576         onViewStateRestored(savedInstanceState);
577         if (!mCalled) {
578             throw new SuperNotCalledException("Fragment " + this
579                     + " did not call through to super.onViewStateRestored()");
580         }
581     }
582 
setIndex(int index, Fragment parent)583     final void setIndex(int index, Fragment parent) {
584         mIndex = index;
585         if (parent != null) {
586             mWho = parent.mWho + ":" + mIndex;
587         } else {
588             mWho = "android:fragment:" + mIndex;
589         }
590     }
591 
isInBackStack()592     final boolean isInBackStack() {
593         return mBackStackNesting > 0;
594     }
595 
596     /**
597      * Subclasses can not override equals().
598      */
equals(Object o)599     @Override final public boolean equals(Object o) {
600         return super.equals(o);
601     }
602 
603     /**
604      * Subclasses can not override hashCode().
605      */
hashCode()606     @Override final public int hashCode() {
607         return super.hashCode();
608     }
609 
610     @Override
toString()611     public String toString() {
612         StringBuilder sb = new StringBuilder(128);
613         DebugUtils.buildShortClassTag(this, sb);
614         if (mIndex >= 0) {
615             sb.append(" #");
616             sb.append(mIndex);
617         }
618         if (mFragmentId != 0) {
619             sb.append(" id=0x");
620             sb.append(Integer.toHexString(mFragmentId));
621         }
622         if (mTag != null) {
623             sb.append(" ");
624             sb.append(mTag);
625         }
626         sb.append('}');
627         return sb.toString();
628     }
629 
630     /**
631      * Return the identifier this fragment is known by.  This is either
632      * the android:id value supplied in a layout or the container view ID
633      * supplied when adding the fragment.
634      */
getId()635     final public int getId() {
636         return mFragmentId;
637     }
638 
639     /**
640      * Get the tag name of the fragment, if specified.
641      */
getTag()642     final public String getTag() {
643         return mTag;
644     }
645 
646     /**
647      * Supply the construction arguments for this fragment.
648      * The arguments supplied here will be retained across fragment destroy and
649      * creation.
650      *
651      * <p>This method cannot be called if the fragment is added to a FragmentManager and
652      * if {@link #isStateSaved()} would return true. Prior to {@link Build.VERSION_CODES#O},
653      * this method may only be called if the fragment has not yet been added to a FragmentManager.
654      * </p>
655      */
setArguments(Bundle args)656     public void setArguments(Bundle args) {
657         // The isStateSaved requirement below was only added in Android O and is compatible
658         // because it loosens previous requirements rather than making them more strict.
659         // See method javadoc.
660         if (mIndex >= 0 && isStateSaved()) {
661             throw new IllegalStateException("Fragment already active");
662         }
663         mArguments = args;
664     }
665 
666     /**
667      * Return the arguments supplied to {@link #setArguments}, if any.
668      */
getArguments()669     final public Bundle getArguments() {
670         return mArguments;
671     }
672 
673     /**
674      * Returns true if this fragment is added and its state has already been saved
675      * by its host. Any operations that would change saved state should not be performed
676      * if this method returns true, and some operations such as {@link #setArguments(Bundle)}
677      * will fail.
678      *
679      * @return true if this fragment's state has already been saved by its host
680      */
isStateSaved()681     public final boolean isStateSaved() {
682         if (mFragmentManager == null) {
683             return false;
684         }
685         return mFragmentManager.isStateSaved();
686     }
687 
688     /**
689      * Set the initial saved state that this Fragment should restore itself
690      * from when first being constructed, as returned by
691      * {@link FragmentManager#saveFragmentInstanceState(Fragment)
692      * FragmentManager.saveFragmentInstanceState}.
693      *
694      * @param state The state the fragment should be restored from.
695      */
setInitialSavedState(SavedState state)696     public void setInitialSavedState(SavedState state) {
697         if (mIndex >= 0) {
698             throw new IllegalStateException("Fragment already active");
699         }
700         mSavedFragmentState = state != null && state.mState != null
701                 ? state.mState : null;
702     }
703 
704     /**
705      * Optional target for this fragment.  This may be used, for example,
706      * if this fragment is being started by another, and when done wants to
707      * give a result back to the first.  The target set here is retained
708      * across instances via {@link FragmentManager#putFragment
709      * FragmentManager.putFragment()}.
710      *
711      * @param fragment The fragment that is the target of this one.
712      * @param requestCode Optional request code, for convenience if you
713      * are going to call back with {@link #onActivityResult(int, int, Intent)}.
714      */
setTargetFragment(Fragment fragment, int requestCode)715     public void setTargetFragment(Fragment fragment, int requestCode) {
716         // Don't allow a caller to set a target fragment in another FragmentManager,
717         // but there's a snag: people do set target fragments before fragments get added.
718         // We'll have the FragmentManager check that for validity when we move
719         // the fragments to a valid state.
720         final FragmentManager mine = getFragmentManager();
721         final FragmentManager theirs = fragment != null ? fragment.getFragmentManager() : null;
722         if (mine != null && theirs != null && mine != theirs) {
723             throw new IllegalArgumentException("Fragment " + fragment
724                     + " must share the same FragmentManager to be set as a target fragment");
725         }
726 
727         // Don't let someone create a cycle.
728         for (Fragment check = fragment; check != null; check = check.getTargetFragment()) {
729             if (check == this) {
730                 throw new IllegalArgumentException("Setting " + fragment + " as the target of "
731                         + this + " would create a target cycle");
732             }
733         }
734         mTarget = fragment;
735         mTargetRequestCode = requestCode;
736     }
737 
738     /**
739      * Return the target fragment set by {@link #setTargetFragment}.
740      */
getTargetFragment()741     final public Fragment getTargetFragment() {
742         return mTarget;
743     }
744 
745     /**
746      * Return the target request code set by {@link #setTargetFragment}.
747      */
getTargetRequestCode()748     final public int getTargetRequestCode() {
749         return mTargetRequestCode;
750     }
751 
752     /**
753      * Return the {@link Context} this fragment is currently associated with.
754      */
getContext()755     public Context getContext() {
756         return mHost == null ? null : mHost.getContext();
757     }
758 
759     /**
760      * Return the Activity this fragment is currently associated with.
761      */
getActivity()762     final public Activity getActivity() {
763         return mHost == null ? null : mHost.getActivity();
764     }
765 
766     /**
767      * Return the host object of this fragment. May return {@code null} if the fragment
768      * isn't currently being hosted.
769      */
770     @Nullable
getHost()771     final public Object getHost() {
772         return mHost == null ? null : mHost.onGetHost();
773     }
774 
775     /**
776      * Return <code>getActivity().getResources()</code>.
777      */
getResources()778     final public Resources getResources() {
779         if (mHost == null) {
780             throw new IllegalStateException("Fragment " + this + " not attached to Activity");
781         }
782         return mHost.getContext().getResources();
783     }
784 
785     /**
786      * Return a localized, styled CharSequence from the application's package's
787      * default string table.
788      *
789      * @param resId Resource id for the CharSequence text
790      */
getText(@tringRes int resId)791     public final CharSequence getText(@StringRes int resId) {
792         return getResources().getText(resId);
793     }
794 
795     /**
796      * Return a localized string from the application's package's
797      * default string table.
798      *
799      * @param resId Resource id for the string
800      */
getString(@tringRes int resId)801     public final String getString(@StringRes int resId) {
802         return getResources().getString(resId);
803     }
804 
805     /**
806      * Return a localized formatted string from the application's package's
807      * default string table, substituting the format arguments as defined in
808      * {@link java.util.Formatter} and {@link java.lang.String#format}.
809      *
810      * @param resId Resource id for the format string
811      * @param formatArgs The format arguments that will be used for substitution.
812      */
813 
getString(@tringRes int resId, Object... formatArgs)814     public final String getString(@StringRes int resId, Object... formatArgs) {
815         return getResources().getString(resId, formatArgs);
816     }
817 
818     /**
819      * Return the FragmentManager for interacting with fragments associated
820      * with this fragment's activity.  Note that this will be non-null slightly
821      * before {@link #getActivity()}, during the time from when the fragment is
822      * placed in a {@link FragmentTransaction} until it is committed and
823      * attached to its activity.
824      *
825      * <p>If this Fragment is a child of another Fragment, the FragmentManager
826      * returned here will be the parent's {@link #getChildFragmentManager()}.
827      */
getFragmentManager()828     final public FragmentManager getFragmentManager() {
829         return mFragmentManager;
830     }
831 
832     /**
833      * Return a private FragmentManager for placing and managing Fragments
834      * inside of this Fragment.
835      */
getChildFragmentManager()836     final public FragmentManager getChildFragmentManager() {
837         if (mChildFragmentManager == null) {
838             instantiateChildFragmentManager();
839             if (mState >= RESUMED) {
840                 mChildFragmentManager.dispatchResume();
841             } else if (mState >= STARTED) {
842                 mChildFragmentManager.dispatchStart();
843             } else if (mState >= ACTIVITY_CREATED) {
844                 mChildFragmentManager.dispatchActivityCreated();
845             } else if (mState >= CREATED) {
846                 mChildFragmentManager.dispatchCreate();
847             }
848         }
849         return mChildFragmentManager;
850     }
851 
852     /**
853      * Returns the parent Fragment containing this Fragment.  If this Fragment
854      * is attached directly to an Activity, returns null.
855      */
getParentFragment()856     final public Fragment getParentFragment() {
857         return mParentFragment;
858     }
859 
860     /**
861      * Return true if the fragment is currently added to its activity.
862      */
isAdded()863     final public boolean isAdded() {
864         return mHost != null && mAdded;
865     }
866 
867     /**
868      * Return true if the fragment has been explicitly detached from the UI.
869      * That is, {@link FragmentTransaction#detach(Fragment)
870      * FragmentTransaction.detach(Fragment)} has been used on it.
871      */
isDetached()872     final public boolean isDetached() {
873         return mDetached;
874     }
875 
876     /**
877      * Return true if this fragment is currently being removed from its
878      * activity.  This is  <em>not</em> whether its activity is finishing, but
879      * rather whether it is in the process of being removed from its activity.
880      */
isRemoving()881     final public boolean isRemoving() {
882         return mRemoving;
883     }
884 
885     /**
886      * Return true if the layout is included as part of an activity view
887      * hierarchy via the &lt;fragment&gt; tag.  This will always be true when
888      * fragments are created through the &lt;fragment&gt; tag, <em>except</em>
889      * in the case where an old fragment is restored from a previous state and
890      * it does not appear in the layout of the current state.
891      */
isInLayout()892     final public boolean isInLayout() {
893         return mInLayout;
894     }
895 
896     /**
897      * Return true if the fragment is in the resumed state.  This is true
898      * for the duration of {@link #onResume()} and {@link #onPause()} as well.
899      */
isResumed()900     final public boolean isResumed() {
901         return mState >= RESUMED;
902     }
903 
904     /**
905      * Return true if the fragment is currently visible to the user.  This means
906      * it: (1) has been added, (2) has its view attached to the window, and
907      * (3) is not hidden.
908      */
isVisible()909     final public boolean isVisible() {
910         return isAdded() && !isHidden() && mView != null
911                 && mView.getWindowToken() != null && mView.getVisibility() == View.VISIBLE;
912     }
913 
914     /**
915      * Return true if the fragment has been hidden.  By default fragments
916      * are shown.  You can find out about changes to this state with
917      * {@link #onHiddenChanged}.  Note that the hidden state is orthogonal
918      * to other states -- that is, to be visible to the user, a fragment
919      * must be both started and not hidden.
920      */
isHidden()921     final public boolean isHidden() {
922         return mHidden;
923     }
924 
925     /**
926      * Called when the hidden state (as returned by {@link #isHidden()} of
927      * the fragment has changed.  Fragments start out not hidden; this will
928      * be called whenever the fragment changes state from that.
929      * @param hidden True if the fragment is now hidden, false otherwise.
930      */
onHiddenChanged(boolean hidden)931     public void onHiddenChanged(boolean hidden) {
932     }
933 
934     /**
935      * Control whether a fragment instance is retained across Activity
936      * re-creation (such as from a configuration change).  This can only
937      * be used with fragments not in the back stack.  If set, the fragment
938      * lifecycle will be slightly different when an activity is recreated:
939      * <ul>
940      * <li> {@link #onDestroy()} will not be called (but {@link #onDetach()} still
941      * will be, because the fragment is being detached from its current activity).
942      * <li> {@link #onCreate(Bundle)} will not be called since the fragment
943      * is not being re-created.
944      * <li> {@link #onAttach(Activity)} and {@link #onActivityCreated(Bundle)} <b>will</b>
945      * still be called.
946      * </ul>
947      */
setRetainInstance(boolean retain)948     public void setRetainInstance(boolean retain) {
949         mRetainInstance = retain;
950     }
951 
getRetainInstance()952     final public boolean getRetainInstance() {
953         return mRetainInstance;
954     }
955 
956     /**
957      * Report that this fragment would like to participate in populating
958      * the options menu by receiving a call to {@link #onCreateOptionsMenu}
959      * and related methods.
960      *
961      * @param hasMenu If true, the fragment has menu items to contribute.
962      */
setHasOptionsMenu(boolean hasMenu)963     public void setHasOptionsMenu(boolean hasMenu) {
964         if (mHasMenu != hasMenu) {
965             mHasMenu = hasMenu;
966             if (isAdded() && !isHidden()) {
967                 mFragmentManager.invalidateOptionsMenu();
968             }
969         }
970     }
971 
972     /**
973      * Set a hint for whether this fragment's menu should be visible.  This
974      * is useful if you know that a fragment has been placed in your view
975      * hierarchy so that the user can not currently seen it, so any menu items
976      * it has should also not be shown.
977      *
978      * @param menuVisible The default is true, meaning the fragment's menu will
979      * be shown as usual.  If false, the user will not see the menu.
980      */
setMenuVisibility(boolean menuVisible)981     public void setMenuVisibility(boolean menuVisible) {
982         if (mMenuVisible != menuVisible) {
983             mMenuVisible = menuVisible;
984             if (mHasMenu && isAdded() && !isHidden()) {
985                 mFragmentManager.invalidateOptionsMenu();
986             }
987         }
988     }
989 
990     /**
991      * Set a hint to the system about whether this fragment's UI is currently visible
992      * to the user. This hint defaults to true and is persistent across fragment instance
993      * state save and restore.
994      *
995      * <p>An app may set this to false to indicate that the fragment's UI is
996      * scrolled out of visibility or is otherwise not directly visible to the user.
997      * This may be used by the system to prioritize operations such as fragment lifecycle updates
998      * or loader ordering behavior.</p>
999      *
1000      * <p><strong>Note:</strong> This method may be called outside of the fragment lifecycle
1001      * and thus has no ordering guarantees with regard to fragment lifecycle method calls.</p>
1002      *
1003      * <p><strong>Note:</strong> Prior to Android N there was a platform bug that could cause
1004      * <code>setUserVisibleHint</code> to bring a fragment up to the started state before its
1005      * <code>FragmentTransaction</code> had been committed. As some apps relied on this behavior,
1006      * it is preserved for apps that declare a <code>targetSdkVersion</code> of 23 or lower.</p>
1007      *
1008      * @param isVisibleToUser true if this fragment's UI is currently visible to the user (default),
1009      *                        false if it is not.
1010      */
setUserVisibleHint(boolean isVisibleToUser)1011     public void setUserVisibleHint(boolean isVisibleToUser) {
1012         // Prior to Android N we were simply checking if this fragment had a FragmentManager
1013         // set before we would trigger a deferred start. Unfortunately this also gets set before
1014         // a fragment transaction is committed, so if setUserVisibleHint was called before a
1015         // transaction commit, we would start the fragment way too early. FragmentPagerAdapter
1016         // triggers this situation.
1017         // Unfortunately some apps relied on this timing in overrides of setUserVisibleHint
1018         // on their own fragments, and expected, however erroneously, that after a call to
1019         // super.setUserVisibleHint their onStart methods had been run.
1020         // We preserve this behavior for apps targeting old platform versions below.
1021         boolean useBrokenAddedCheck = false;
1022         Context context = getContext();
1023         if (mFragmentManager != null && mFragmentManager.mHost != null) {
1024             context = mFragmentManager.mHost.getContext();
1025         }
1026         if (context != null) {
1027             useBrokenAddedCheck = context.getApplicationInfo().targetSdkVersion <= VERSION_CODES.M;
1028         }
1029 
1030         final boolean performDeferredStart;
1031         if (useBrokenAddedCheck) {
1032             performDeferredStart = !mUserVisibleHint && isVisibleToUser && mState < STARTED
1033                     && mFragmentManager != null;
1034         } else {
1035             performDeferredStart = !mUserVisibleHint && isVisibleToUser && mState < STARTED
1036                     && mFragmentManager != null && isAdded();
1037         }
1038 
1039         if (performDeferredStart) {
1040             mFragmentManager.performPendingDeferredStart(this);
1041         }
1042 
1043         mUserVisibleHint = isVisibleToUser;
1044         mDeferStart = mState < STARTED && !isVisibleToUser;
1045     }
1046 
1047     /**
1048      * @return The current value of the user-visible hint on this fragment.
1049      * @see #setUserVisibleHint(boolean)
1050      */
1051     public boolean getUserVisibleHint() {
1052         return mUserVisibleHint;
1053     }
1054 
1055     /**
1056      * Return the LoaderManager for this fragment, creating it if needed.
1057      *
1058      * @deprecated Use {@link android.support.v4.app.Fragment#getLoaderManager()}
1059      */
1060     @Deprecated
1061     public LoaderManager getLoaderManager() {
1062         if (mLoaderManager != null) {
1063             return mLoaderManager;
1064         }
1065         if (mHost == null) {
1066             throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1067         }
1068         mCheckedForLoaderManager = true;
1069         mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, true);
1070         return mLoaderManager;
1071     }
1072 
1073     /**
1074      * Call {@link Activity#startActivity(Intent)} from the fragment's
1075      * containing Activity.
1076      *
1077      * @param intent The intent to start.
1078      */
1079     public void startActivity(Intent intent) {
1080         startActivity(intent, null);
1081     }
1082 
1083     /**
1084      * Call {@link Activity#startActivity(Intent, Bundle)} from the fragment's
1085      * containing Activity.
1086      *
1087      * @param intent The intent to start.
1088      * @param options Additional options for how the Activity should be started.
1089      * See {@link android.content.Context#startActivity(Intent, Bundle)}
1090      * Context.startActivity(Intent, Bundle)} for more details.
1091      */
1092     public void startActivity(Intent intent, Bundle options) {
1093         if (mHost == null) {
1094             throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1095         }
1096         if (options != null) {
1097             mHost.onStartActivityFromFragment(this, intent, -1, options);
1098         } else {
1099             // Note we want to go through this call for compatibility with
1100             // applications that may have overridden the method.
1101             mHost.onStartActivityFromFragment(this, intent, -1, null /*options*/);
1102         }
1103     }
1104 
1105     /**
1106      * Call {@link Activity#startActivityForResult(Intent, int)} from the fragment's
1107      * containing Activity.
1108      */
1109     public void startActivityForResult(Intent intent, int requestCode) {
1110         startActivityForResult(intent, requestCode, null);
1111     }
1112 
1113     /**
1114      * Call {@link Activity#startActivityForResult(Intent, int, Bundle)} from the fragment's
1115      * containing Activity.
1116      */
1117     public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
1118         if (mHost == null) {
1119             throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1120         }
1121         mHost.onStartActivityFromFragment(this, intent, requestCode, options);
1122     }
1123 
1124     /**
1125      * @hide
1126      * Call {@link Activity#startActivityForResultAsUser(Intent, int, UserHandle)} from the
1127      * fragment's containing Activity.
1128      */
1129     public void startActivityForResultAsUser(
1130             Intent intent, int requestCode, Bundle options, UserHandle user) {
1131         if (mHost == null) {
1132             throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1133         }
1134         mHost.onStartActivityAsUserFromFragment(this, intent, requestCode, options, user);
1135     }
1136 
1137     /**
1138      * Call {@link Activity#startIntentSenderForResult(IntentSender, int, Intent, int, int, int,
1139      * Bundle)} from the fragment's containing Activity.
1140      */
1141     public void startIntentSenderForResult(IntentSender intent, int requestCode,
1142             @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
1143             Bundle options) throws IntentSender.SendIntentException {
1144         if (mHost == null) {
1145             throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1146         }
1147         mHost.onStartIntentSenderFromFragment(this, intent, requestCode, fillInIntent, flagsMask,
1148                 flagsValues, extraFlags, options);
1149     }
1150 
1151     /**
1152      * Receive the result from a previous call to
1153      * {@link #startActivityForResult(Intent, int)}.  This follows the
1154      * related Activity API as described there in
1155      * {@link Activity#onActivityResult(int, int, Intent)}.
1156      *
1157      * @param requestCode The integer request code originally supplied to
1158      *                    startActivityForResult(), allowing you to identify who this
1159      *                    result came from.
1160      * @param resultCode The integer result code returned by the child activity
1161      *                   through its setResult().
1162      * @param data An Intent, which can return result data to the caller
1163      *               (various data can be attached to Intent "extras").
1164      */
1165     public void onActivityResult(int requestCode, int resultCode, Intent data) {
1166     }
1167 
1168     /**
1169      * Requests permissions to be granted to this application. These permissions
1170      * must be requested in your manifest, they should not be granted to your app,
1171      * and they should have protection level {@link android.content.pm.PermissionInfo
1172      * #PROTECTION_DANGEROUS dangerous}, regardless whether they are declared by
1173      * the platform or a third-party app.
1174      * <p>
1175      * Normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_NORMAL}
1176      * are granted at install time if requested in the manifest. Signature permissions
1177      * {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at
1178      * install time if requested in the manifest and the signature of your app matches
1179      * the signature of the app declaring the permissions.
1180      * </p>
1181      * <p>
1182      * Call {@link #shouldShowRequestPermissionRationale(String)} before calling this API
1183      * to check if the system recommends to show a rationale UI before asking for a permission.
1184      * </p>
1185      * <p>
1186      * If your app does not have the requested permissions the user will be presented
1187      * with UI for accepting them. After the user has accepted or rejected the
1188      * requested permissions you will receive a callback on {@link
1189      * #onRequestPermissionsResult(int, String[], int[])} reporting whether the
1190      * permissions were granted or not.
1191      * </p>
1192      * <p>
1193      * Note that requesting a permission does not guarantee it will be granted and
1194      * your app should be able to run without having this permission.
1195      * </p>
1196      * <p>
1197      * This method may start an activity allowing the user to choose which permissions
1198      * to grant and which to reject. Hence, you should be prepared that your activity
1199      * may be paused and resumed. Further, granting some permissions may require
1200      * a restart of you application. In such a case, the system will recreate the
1201      * activity stack before delivering the result to {@link
1202      * #onRequestPermissionsResult(int, String[], int[])}.
1203      * </p>
1204      * <p>
1205      * When checking whether you have a permission you should use {@link
1206      * android.content.Context#checkSelfPermission(String)}.
1207      * </p>
1208      * <p>
1209      * Calling this API for permissions already granted to your app would show UI
1210      * to the user to decide whether the app can still hold these permissions. This
1211      * can be useful if the way your app uses data guarded by the permissions
1212      * changes significantly.
1213      * </p>
1214      * <p>
1215      * You cannot request a permission if your activity sets {@link
1216      * android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
1217      * <code>true</code> because in this case the activity would not receive
1218      * result callbacks including {@link #onRequestPermissionsResult(int, String[], int[])}.
1219      * </p>
1220      *
1221      * @param permissions The requested permissions. Must me non-null and not empty.
1222      * @param requestCode Application specific request code to match with a result
1223      *    reported to {@link #onRequestPermissionsResult(int, String[], int[])}.
1224      *    Should be >= 0.
1225      *
1226      * @see #onRequestPermissionsResult(int, String[], int[])
1227      * @see android.content.Context#checkSelfPermission(String)
1228      */
1229     public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
1230         if (mHost == null) {
1231             throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1232         }
1233         mHost.onRequestPermissionsFromFragment(this, permissions,requestCode);
1234     }
1235 
1236     /**
1237      * Callback for the result from requesting permissions. This method
1238      * is invoked for every call on {@link #requestPermissions(String[], int)}.
1239      * <p>
1240      * <strong>Note:</strong> It is possible that the permissions request interaction
1241      * with the user is interrupted. In this case you will receive empty permissions
1242      * and results arrays which should be treated as a cancellation.
1243      * </p>
1244      *
1245      * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
1246      * @param permissions The requested permissions. Never null.
1247      * @param grantResults The grant results for the corresponding permissions
1248      *     which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED}
1249      *     or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null.
1250      *
1251      * @see #requestPermissions(String[], int)
1252      */
1253     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
1254             @NonNull int[] grantResults) {
1255         /* callback - do nothing */
1256     }
1257 
1258     /**
1259      * Gets whether you should show UI with rationale before requesting a permission.
1260      *
1261      * @param permission A permission your app wants to request.
1262      * @return Whether you should show permission rationale UI.
1263      *
1264      * @see Context#checkSelfPermission(String)
1265      * @see #requestPermissions(String[], int)
1266      * @see #onRequestPermissionsResult(int, String[], int[])
1267      */
1268     public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
1269         if (mHost != null) {
1270             return mHost.getContext().getPackageManager()
1271                     .shouldShowRequestPermissionRationale(permission);
1272         }
1273         return false;
1274     }
1275 
1276     /**
1277      * Returns the LayoutInflater used to inflate Views of this Fragment. The default
1278      * implementation will throw an exception if the Fragment is not attached.
1279      *
1280      * @return The LayoutInflater used to inflate Views of this Fragment.
1281      */
1282     public LayoutInflater onGetLayoutInflater(Bundle savedInstanceState) {
1283         if (mHost == null) {
1284             throw new IllegalStateException("onGetLayoutInflater() cannot be executed until the "
1285                     + "Fragment is attached to the FragmentManager.");
1286         }
1287         final LayoutInflater result = mHost.onGetLayoutInflater();
1288         if (mHost.onUseFragmentManagerInflaterFactory()) {
1289             getChildFragmentManager(); // Init if needed; use raw implementation below.
1290             result.setPrivateFactory(mChildFragmentManager.getLayoutInflaterFactory());
1291         }
1292         return result;
1293     }
1294 
1295     /**
1296      * Returns the cached LayoutInflater used to inflate Views of this Fragment. If
1297      * {@link #onGetLayoutInflater(Bundle)} has not been called {@link #onGetLayoutInflater(Bundle)}
1298      * will be called with a {@code null} argument and that value will be cached.
1299      * <p>
1300      * The cached LayoutInflater will be replaced immediately prior to
1301      * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)} and cleared immediately after
1302      * {@link #onDetach()}.
1303      *
1304      * @return The LayoutInflater used to inflate Views of this Fragment.
1305      */
1306     public final LayoutInflater getLayoutInflater() {
1307         if (mLayoutInflater == null) {
1308             return performGetLayoutInflater(null);
1309         }
1310         return mLayoutInflater;
1311     }
1312 
1313     /**
1314      * Calls {@link #onGetLayoutInflater(Bundle)} and caches the result for use by
1315      * {@link #getLayoutInflater()}.
1316      *
1317      * @param savedInstanceState If the fragment is being re-created from
1318      * a previous saved state, this is the state.
1319      * @return The LayoutInflater used to inflate Views of this Fragment.
1320      */
1321     LayoutInflater performGetLayoutInflater(Bundle savedInstanceState) {
1322         LayoutInflater layoutInflater = onGetLayoutInflater(savedInstanceState);
1323         mLayoutInflater = layoutInflater;
1324         return mLayoutInflater;
1325     }
1326 
1327     /**
1328      * @deprecated Use {@link #onInflate(Context, AttributeSet, Bundle)} instead.
1329      */
1330     @Deprecated
1331     @CallSuper
1332     public void onInflate(AttributeSet attrs, Bundle savedInstanceState) {
1333         mCalled = true;
1334     }
1335 
1336     /**
1337      * Called when a fragment is being created as part of a view layout
1338      * inflation, typically from setting the content view of an activity.  This
1339      * may be called immediately after the fragment is created from a <fragment>
1340      * tag in a layout file.  Note this is <em>before</em> the fragment's
1341      * {@link #onAttach(Activity)} has been called; all you should do here is
1342      * parse the attributes and save them away.
1343      *
1344      * <p>This is called every time the fragment is inflated, even if it is
1345      * being inflated into a new instance with saved state.  It typically makes
1346      * sense to re-parse the parameters each time, to allow them to change with
1347      * different configurations.</p>
1348      *
1349      * <p>Here is a typical implementation of a fragment that can take parameters
1350      * both through attributes supplied here as well from {@link #getArguments()}:</p>
1351      *
1352      * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
1353      *      fragment}
1354      *
1355      * <p>Note that parsing the XML attributes uses a "styleable" resource.  The
1356      * declaration for the styleable used here is:</p>
1357      *
1358      * {@sample development/samples/ApiDemos/res/values/attrs.xml fragment_arguments}
1359      *
1360      * <p>The fragment can then be declared within its activity's content layout
1361      * through a tag like this:</p>
1362      *
1363      * {@sample development/samples/ApiDemos/res/layout/fragment_arguments.xml from_attributes}
1364      *
1365      * <p>This fragment can also be created dynamically from arguments given
1366      * at runtime in the arguments Bundle; here is an example of doing so at
1367      * creation of the containing activity:</p>
1368      *
1369      * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
1370      *      create}
1371      *
1372      * @param context The Context that is inflating this fragment.
1373      * @param attrs The attributes at the tag where the fragment is
1374      * being created.
1375      * @param savedInstanceState If the fragment is being re-created from
1376      * a previous saved state, this is the state.
1377      */
1378     @CallSuper
1379     public void onInflate(Context context, AttributeSet attrs, Bundle savedInstanceState) {
1380         onInflate(attrs, savedInstanceState);
1381         mCalled = true;
1382 
1383         TypedArray a = context.obtainStyledAttributes(attrs,
1384                 com.android.internal.R.styleable.Fragment);
1385         setEnterTransition(loadTransition(context, a, getEnterTransition(), null,
1386                 com.android.internal.R.styleable.Fragment_fragmentEnterTransition));
1387         setReturnTransition(loadTransition(context, a, getReturnTransition(),
1388                 USE_DEFAULT_TRANSITION,
1389                 com.android.internal.R.styleable.Fragment_fragmentReturnTransition));
1390         setExitTransition(loadTransition(context, a, getExitTransition(), null,
1391                 com.android.internal.R.styleable.Fragment_fragmentExitTransition));
1392 
1393         setReenterTransition(loadTransition(context, a, getReenterTransition(),
1394                 USE_DEFAULT_TRANSITION,
1395                 com.android.internal.R.styleable.Fragment_fragmentReenterTransition));
1396         setSharedElementEnterTransition(loadTransition(context, a,
1397                 getSharedElementEnterTransition(), null,
1398                 com.android.internal.R.styleable.Fragment_fragmentSharedElementEnterTransition));
1399         setSharedElementReturnTransition(loadTransition(context, a,
1400                 getSharedElementReturnTransition(), USE_DEFAULT_TRANSITION,
1401                 com.android.internal.R.styleable.Fragment_fragmentSharedElementReturnTransition));
1402         boolean isEnterSet;
1403         boolean isReturnSet;
1404         if (mAnimationInfo == null) {
1405             isEnterSet = false;
1406             isReturnSet = false;
1407         } else {
1408             isEnterSet = mAnimationInfo.mAllowEnterTransitionOverlap != null;
1409             isReturnSet = mAnimationInfo.mAllowReturnTransitionOverlap != null;
1410         }
1411         if (!isEnterSet) {
1412             setAllowEnterTransitionOverlap(a.getBoolean(
1413                     com.android.internal.R.styleable.Fragment_fragmentAllowEnterTransitionOverlap,
1414                     true));
1415         }
1416         if (!isReturnSet) {
1417             setAllowReturnTransitionOverlap(a.getBoolean(
1418                     com.android.internal.R.styleable.Fragment_fragmentAllowReturnTransitionOverlap,
1419                     true));
1420         }
1421         a.recycle();
1422 
1423         final Activity hostActivity = mHost == null ? null : mHost.getActivity();
1424         if (hostActivity != null) {
1425             mCalled = false;
1426             onInflate(hostActivity, attrs, savedInstanceState);
1427         }
1428     }
1429 
1430     /**
1431      * @deprecated Use {@link #onInflate(Context, AttributeSet, Bundle)} instead.
1432      */
1433     @Deprecated
1434     @CallSuper
1435     public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
1436         mCalled = true;
1437     }
1438 
1439     /**
1440      * Called when a fragment is attached as a child of this fragment.
1441      *
1442      * <p>This is called after the attached fragment's <code>onAttach</code> and before
1443      * the attached fragment's <code>onCreate</code> if the fragment has not yet had a previous
1444      * call to <code>onCreate</code>.</p>
1445      *
1446      * @param childFragment child fragment being attached
1447      */
1448     public void onAttachFragment(Fragment childFragment) {
1449     }
1450 
1451     /**
1452      * Called when a fragment is first attached to its context.
1453      * {@link #onCreate(Bundle)} will be called after this.
1454      */
1455     @CallSuper
1456     public void onAttach(Context context) {
1457         mCalled = true;
1458         final Activity hostActivity = mHost == null ? null : mHost.getActivity();
1459         if (hostActivity != null) {
1460             mCalled = false;
1461             onAttach(hostActivity);
1462         }
1463     }
1464 
1465     /**
1466      * @deprecated Use {@link #onAttach(Context)} instead.
1467      */
1468     @Deprecated
1469     @CallSuper
1470     public void onAttach(Activity activity) {
1471         mCalled = true;
1472     }
1473 
1474     /**
1475      * Called when a fragment loads an animation.
1476      */
1477     public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) {
1478         return null;
1479     }
1480 
1481     /**
1482      * Called to do initial creation of a fragment.  This is called after
1483      * {@link #onAttach(Activity)} and before
1484      * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}, but is not called if the fragment
1485      * instance is retained across Activity re-creation (see {@link #setRetainInstance(boolean)}).
1486      *
1487      * <p>Note that this can be called while the fragment's activity is
1488      * still in the process of being created.  As such, you can not rely
1489      * on things like the activity's content view hierarchy being initialized
1490      * at this point.  If you want to do work once the activity itself is
1491      * created, see {@link #onActivityCreated(Bundle)}.
1492      *
1493      * <p>If your app's <code>targetSdkVersion</code> is {@link android.os.Build.VERSION_CODES#M}
1494      * or lower, child fragments being restored from the savedInstanceState are restored after
1495      * <code>onCreate</code> returns. When targeting {@link android.os.Build.VERSION_CODES#N} or
1496      * above and running on an N or newer platform version
1497      * they are restored by <code>Fragment.onCreate</code>.</p>
1498      *
1499      * @param savedInstanceState If the fragment is being re-created from
1500      * a previous saved state, this is the state.
1501      */
1502     @CallSuper
1503     public void onCreate(@Nullable Bundle savedInstanceState) {
1504         mCalled = true;
1505         final Context context = getContext();
1506         final int version = context != null ? context.getApplicationInfo().targetSdkVersion : 0;
1507         if (version >= Build.VERSION_CODES.N) {
1508             restoreChildFragmentState(savedInstanceState, true);
1509             if (mChildFragmentManager != null
1510                     && !mChildFragmentManager.isStateAtLeast(Fragment.CREATED)) {
1511                 mChildFragmentManager.dispatchCreate();
1512             }
1513         }
1514     }
1515 
1516     void restoreChildFragmentState(@Nullable Bundle savedInstanceState, boolean provideNonConfig) {
1517         if (savedInstanceState != null) {
1518             Parcelable p = savedInstanceState.getParcelable(Activity.FRAGMENTS_TAG);
1519             if (p != null) {
1520                 if (mChildFragmentManager == null) {
1521                     instantiateChildFragmentManager();
1522                 }
1523                 mChildFragmentManager.restoreAllState(p, provideNonConfig ? mChildNonConfig : null);
1524                 mChildNonConfig = null;
1525                 mChildFragmentManager.dispatchCreate();
1526             }
1527         }
1528     }
1529 
1530     /**
1531      * Called to have the fragment instantiate its user interface view.
1532      * This is optional, and non-graphical fragments can return null (which
1533      * is the default implementation).  This will be called between
1534      * {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}.
1535      *
1536      * <p>If you return a View from here, you will later be called in
1537      * {@link #onDestroyView} when the view is being released.
1538      *
1539      * @param inflater The LayoutInflater object that can be used to inflate
1540      * any views in the fragment,
1541      * @param container If non-null, this is the parent view that the fragment's
1542      * UI should be attached to.  The fragment should not add the view itself,
1543      * but this can be used to generate the LayoutParams of the view.
1544      * @param savedInstanceState If non-null, this fragment is being re-constructed
1545      * from a previous saved state as given here.
1546      *
1547      * @return Return the View for the fragment's UI, or null.
1548      */
1549     @Nullable
1550     public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
1551             Bundle savedInstanceState) {
1552         return null;
1553     }
1554 
1555     /**
1556      * Called immediately after {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}
1557      * has returned, but before any saved state has been restored in to the view.
1558      * This gives subclasses a chance to initialize themselves once
1559      * they know their view hierarchy has been completely created.  The fragment's
1560      * view hierarchy is not however attached to its parent at this point.
1561      * @param view The View returned by {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
1562      * @param savedInstanceState If non-null, this fragment is being re-constructed
1563      * from a previous saved state as given here.
1564      */
1565     public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
1566     }
1567 
1568     /**
1569      * Get the root view for the fragment's layout (the one returned by {@link #onCreateView}),
1570      * if provided.
1571      *
1572      * @return The fragment's root view, or null if it has no layout.
1573      */
1574     @Nullable
1575     public View getView() {
1576         return mView;
1577     }
1578 
1579     /**
1580      * Called when the fragment's activity has been created and this
1581      * fragment's view hierarchy instantiated.  It can be used to do final
1582      * initialization once these pieces are in place, such as retrieving
1583      * views or restoring state.  It is also useful for fragments that use
1584      * {@link #setRetainInstance(boolean)} to retain their instance,
1585      * as this callback tells the fragment when it is fully associated with
1586      * the new activity instance.  This is called after {@link #onCreateView}
1587      * and before {@link #onViewStateRestored(Bundle)}.
1588      *
1589      * @param savedInstanceState If the fragment is being re-created from
1590      * a previous saved state, this is the state.
1591      */
1592     @CallSuper
1593     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
1594         mCalled = true;
1595     }
1596 
1597     /**
1598      * Called when all saved state has been restored into the view hierarchy
1599      * of the fragment.  This can be used to do initialization based on saved
1600      * state that you are letting the view hierarchy track itself, such as
1601      * whether check box widgets are currently checked.  This is called
1602      * after {@link #onActivityCreated(Bundle)} and before
1603      * {@link #onStart()}.
1604      *
1605      * @param savedInstanceState If the fragment is being re-created from
1606      * a previous saved state, this is the state.
1607      */
1608     @CallSuper
1609     public void onViewStateRestored(Bundle savedInstanceState) {
1610         mCalled = true;
1611     }
1612 
1613     /**
1614      * Called when the Fragment is visible to the user.  This is generally
1615      * tied to {@link Activity#onStart() Activity.onStart} of the containing
1616      * Activity's lifecycle.
1617      */
1618     @CallSuper
1619     public void onStart() {
1620         mCalled = true;
1621 
1622         if (!mLoadersStarted) {
1623             mLoadersStarted = true;
1624             if (!mCheckedForLoaderManager) {
1625                 mCheckedForLoaderManager = true;
1626                 mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, false);
1627             } else if (mLoaderManager != null) {
1628                 mLoaderManager.doStart();
1629             }
1630         }
1631     }
1632 
1633     /**
1634      * Called when the fragment is visible to the user and actively running.
1635      * This is generally
1636      * tied to {@link Activity#onResume() Activity.onResume} of the containing
1637      * Activity's lifecycle.
1638      */
1639     @CallSuper
1640     public void onResume() {
1641         mCalled = true;
1642     }
1643 
1644     /**
1645      * Called to ask the fragment to save its current dynamic state, so it
1646      * can later be reconstructed in a new instance of its process is
1647      * restarted.  If a new instance of the fragment later needs to be
1648      * created, the data you place in the Bundle here will be available
1649      * in the Bundle given to {@link #onCreate(Bundle)},
1650      * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}, and
1651      * {@link #onActivityCreated(Bundle)}.
1652      *
1653      * <p>This corresponds to {@link Activity#onSaveInstanceState(Bundle)
1654      * Activity.onSaveInstanceState(Bundle)} and most of the discussion there
1655      * applies here as well.  Note however: <em>this method may be called
1656      * at any time before {@link #onDestroy()}</em>.  There are many situations
1657      * where a fragment may be mostly torn down (such as when placed on the
1658      * back stack with no UI showing), but its state will not be saved until
1659      * its owning activity actually needs to save its state.
1660      *
1661      * @param outState Bundle in which to place your saved state.
1662      */
1663     public void onSaveInstanceState(Bundle outState) {
1664     }
1665 
1666     /**
1667      * Called when the Fragment's activity changes from fullscreen mode to multi-window mode and
1668      * visa-versa. This is generally tied to {@link Activity#onMultiWindowModeChanged} of the
1669      * containing Activity. This method provides the same configuration that will be sent in the
1670      * following {@link #onConfigurationChanged(Configuration)} call after the activity enters this
1671      * mode.
1672      *
1673      * @param isInMultiWindowMode True if the activity is in multi-window mode.
1674      * @param newConfig The new configuration of the activity with the state
1675      *                  {@param isInMultiWindowMode}.
1676      */
1677     public void onMultiWindowModeChanged(boolean isInMultiWindowMode, Configuration newConfig) {
1678         onMultiWindowModeChanged(isInMultiWindowMode);
1679     }
1680 
1681     /**
1682      * Called when the Fragment's activity changes from fullscreen mode to multi-window mode and
1683      * visa-versa. This is generally tied to {@link Activity#onMultiWindowModeChanged} of the
1684      * containing Activity.
1685      *
1686      * @param isInMultiWindowMode True if the activity is in multi-window mode.
1687      *
1688      * @deprecated Use {@link #onMultiWindowModeChanged(boolean, Configuration)} instead.
1689      */
1690     @Deprecated
1691     public void onMultiWindowModeChanged(boolean isInMultiWindowMode) {
1692     }
1693 
1694     /**
1695      * Called by the system when the activity changes to and from picture-in-picture mode. This is
1696      * generally tied to {@link Activity#onPictureInPictureModeChanged} of the containing Activity.
1697      * This method provides the same configuration that will be sent in the following
1698      * {@link #onConfigurationChanged(Configuration)} call after the activity enters this mode.
1699      *
1700      * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode.
1701      * @param newConfig The new configuration of the activity with the state
1702      *                  {@param isInPictureInPictureMode}.
1703      */
1704     public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode,
1705             Configuration newConfig) {
1706         onPictureInPictureModeChanged(isInPictureInPictureMode);
1707     }
1708 
1709     /**
1710      * Called by the system when the activity changes to and from picture-in-picture mode. This is
1711      * generally tied to {@link Activity#onPictureInPictureModeChanged} of the containing Activity.
1712      *
1713      * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode.
1714      *
1715      * @deprecated Use {@link #onPictureInPictureModeChanged(boolean, Configuration)} instead.
1716      */
1717     @Deprecated
1718     public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
1719     }
1720 
1721     @CallSuper
1722     public void onConfigurationChanged(Configuration newConfig) {
1723         mCalled = true;
1724     }
1725 
1726     /**
1727      * Called when the Fragment is no longer resumed.  This is generally
1728      * tied to {@link Activity#onPause() Activity.onPause} of the containing
1729      * Activity's lifecycle.
1730      */
1731     @CallSuper
1732     public void onPause() {
1733         mCalled = true;
1734     }
1735 
1736     /**
1737      * Called when the Fragment is no longer started.  This is generally
1738      * tied to {@link Activity#onStop() Activity.onStop} of the containing
1739      * Activity's lifecycle.
1740      */
1741     @CallSuper
1742     public void onStop() {
1743         mCalled = true;
1744     }
1745 
1746     @CallSuper
1747     public void onLowMemory() {
1748         mCalled = true;
1749     }
1750 
1751     @CallSuper
1752     public void onTrimMemory(int level) {
1753         mCalled = true;
1754     }
1755 
1756     /**
1757      * Called when the view previously created by {@link #onCreateView} has
1758      * been detached from the fragment.  The next time the fragment needs
1759      * to be displayed, a new view will be created.  This is called
1760      * after {@link #onStop()} and before {@link #onDestroy()}.  It is called
1761      * <em>regardless</em> of whether {@link #onCreateView} returned a
1762      * non-null view.  Internally it is called after the view's state has
1763      * been saved but before it has been removed from its parent.
1764      */
1765     @CallSuper
1766     public void onDestroyView() {
1767         mCalled = true;
1768     }
1769 
1770     /**
1771      * Called when the fragment is no longer in use.  This is called
1772      * after {@link #onStop()} and before {@link #onDetach()}.
1773      */
1774     @CallSuper
1775     public void onDestroy() {
1776         mCalled = true;
1777         //Log.v("foo", "onDestroy: mCheckedForLoaderManager=" + mCheckedForLoaderManager
1778         //        + " mLoaderManager=" + mLoaderManager);
1779         if (!mCheckedForLoaderManager) {
1780             mCheckedForLoaderManager = true;
1781             mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, false);
1782         }
1783         if (mLoaderManager != null) {
1784             mLoaderManager.doDestroy();
1785         }
1786     }
1787 
1788     /**
1789      * Called by the fragment manager once this fragment has been removed,
1790      * so that we don't have any left-over state if the application decides
1791      * to re-use the instance.  This only clears state that the framework
1792      * internally manages, not things the application sets.
1793      */
1794     void initState() {
1795         mIndex = -1;
1796         mWho = null;
1797         mAdded = false;
1798         mRemoving = false;
1799         mFromLayout = false;
1800         mInLayout = false;
1801         mRestored = false;
1802         mBackStackNesting = 0;
1803         mFragmentManager = null;
1804         mChildFragmentManager = null;
1805         mHost = null;
1806         mFragmentId = 0;
1807         mContainerId = 0;
1808         mTag = null;
1809         mHidden = false;
1810         mDetached = false;
1811         mRetaining = false;
1812         mLoaderManager = null;
1813         mLoadersStarted = false;
1814         mCheckedForLoaderManager = false;
1815     }
1816 
1817     /**
1818      * Called when the fragment is no longer attached to its activity.  This is called after
1819      * {@link #onDestroy()}, except in the cases where the fragment instance is retained across
1820      * Activity re-creation (see {@link #setRetainInstance(boolean)}), in which case it is called
1821      * after {@link #onStop()}.
1822      */
1823     @CallSuper
1824     public void onDetach() {
1825         mCalled = true;
1826     }
1827 
1828     /**
1829      * Initialize the contents of the Activity's standard options menu.  You
1830      * should place your menu items in to <var>menu</var>.  For this method
1831      * to be called, you must have first called {@link #setHasOptionsMenu}.  See
1832      * {@link Activity#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu}
1833      * for more information.
1834      *
1835      * @param menu The options menu in which you place your items.
1836      *
1837      * @see #setHasOptionsMenu
1838      * @see #onPrepareOptionsMenu
1839      * @see #onOptionsItemSelected
1840      */
1841     public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
1842     }
1843 
1844     /**
1845      * Prepare the Screen's standard options menu to be displayed.  This is
1846      * called right before the menu is shown, every time it is shown.  You can
1847      * use this method to efficiently enable/disable items or otherwise
1848      * dynamically modify the contents.  See
1849      * {@link Activity#onPrepareOptionsMenu(Menu) Activity.onPrepareOptionsMenu}
1850      * for more information.
1851      *
1852      * @param menu The options menu as last shown or first initialized by
1853      *             onCreateOptionsMenu().
1854      *
1855      * @see #setHasOptionsMenu
1856      * @see #onCreateOptionsMenu
1857      */
1858     public void onPrepareOptionsMenu(Menu menu) {
1859     }
1860 
1861     /**
1862      * Called when this fragment's option menu items are no longer being
1863      * included in the overall options menu.  Receiving this call means that
1864      * the menu needed to be rebuilt, but this fragment's items were not
1865      * included in the newly built menu (its {@link #onCreateOptionsMenu(Menu, MenuInflater)}
1866      * was not called).
1867      */
1868     public void onDestroyOptionsMenu() {
1869     }
1870 
1871     /**
1872      * This hook is called whenever an item in your options menu is selected.
1873      * The default implementation simply returns false to have the normal
1874      * processing happen (calling the item's Runnable or sending a message to
1875      * its Handler as appropriate).  You can use this method for any items
1876      * for which you would like to do processing without those other
1877      * facilities.
1878      *
1879      * <p>Derived classes should call through to the base class for it to
1880      * perform the default menu handling.
1881      *
1882      * @param item The menu item that was selected.
1883      *
1884      * @return boolean Return false to allow normal menu processing to
1885      *         proceed, true to consume it here.
1886      *
1887      * @see #onCreateOptionsMenu
1888      */
1889     public boolean onOptionsItemSelected(MenuItem item) {
1890         return false;
1891     }
1892 
1893     /**
1894      * This hook is called whenever the options menu is being closed (either by the user canceling
1895      * the menu with the back/menu button, or when an item is selected).
1896      *
1897      * @param menu The options menu as last shown or first initialized by
1898      *             onCreateOptionsMenu().
1899      */
1900     public void onOptionsMenuClosed(Menu menu) {
1901     }
1902 
1903     /**
1904      * Called when a context menu for the {@code view} is about to be shown.
1905      * Unlike {@link #onCreateOptionsMenu}, this will be called every
1906      * time the context menu is about to be shown and should be populated for
1907      * the view (or item inside the view for {@link AdapterView} subclasses,
1908      * this can be found in the {@code menuInfo})).
1909      * <p>
1910      * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
1911      * item has been selected.
1912      * <p>
1913      * The default implementation calls up to
1914      * {@link Activity#onCreateContextMenu Activity.onCreateContextMenu}, though
1915      * you can not call this implementation if you don't want that behavior.
1916      * <p>
1917      * It is not safe to hold onto the context menu after this method returns.
1918      * {@inheritDoc}
1919      */
1920     public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1921         getActivity().onCreateContextMenu(menu, v, menuInfo);
1922     }
1923 
1924     /**
1925      * Registers a context menu to be shown for the given view (multiple views
1926      * can show the context menu). This method will set the
1927      * {@link OnCreateContextMenuListener} on the view to this fragment, so
1928      * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
1929      * called when it is time to show the context menu.
1930      *
1931      * @see #unregisterForContextMenu(View)
1932      * @param view The view that should show a context menu.
1933      */
1934     public void registerForContextMenu(View view) {
1935         view.setOnCreateContextMenuListener(this);
1936     }
1937 
1938     /**
1939      * Prevents a context menu to be shown for the given view. This method will
1940      * remove the {@link OnCreateContextMenuListener} on the view.
1941      *
1942      * @see #registerForContextMenu(View)
1943      * @param view The view that should stop showing a context menu.
1944      */
1945     public void unregisterForContextMenu(View view) {
1946         view.setOnCreateContextMenuListener(null);
1947     }
1948 
1949     /**
1950      * This hook is called whenever an item in a context menu is selected. The
1951      * default implementation simply returns false to have the normal processing
1952      * happen (calling the item's Runnable or sending a message to its Handler
1953      * as appropriate). You can use this method for any items for which you
1954      * would like to do processing without those other facilities.
1955      * <p>
1956      * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
1957      * View that added this menu item.
1958      * <p>
1959      * Derived classes should call through to the base class for it to perform
1960      * the default menu handling.
1961      *
1962      * @param item The context menu item that was selected.
1963      * @return boolean Return false to allow normal context menu processing to
1964      *         proceed, true to consume it here.
1965      */
1966     public boolean onContextItemSelected(MenuItem item) {
1967         return false;
1968     }
1969 
1970     /**
1971      * When custom transitions are used with Fragments, the enter transition callback
1972      * is called when this Fragment is attached or detached when not popping the back stack.
1973      *
1974      * @param callback Used to manipulate the shared element transitions on this Fragment
1975      *                 when added not as a pop from the back stack.
1976      */
1977     public void setEnterSharedElementCallback(SharedElementCallback callback) {
1978         if (callback == null) {
1979             if (mAnimationInfo == null) {
1980                 return; // already a null callback
1981             }
1982             callback = SharedElementCallback.NULL_CALLBACK;
1983         }
1984         ensureAnimationInfo().mEnterTransitionCallback = callback;
1985     }
1986 
1987     /**
1988      * When custom transitions are used with Fragments, the exit transition callback
1989      * is called when this Fragment is attached or detached when popping the back stack.
1990      *
1991      * @param callback Used to manipulate the shared element transitions on this Fragment
1992      *                 when added as a pop from the back stack.
1993      */
1994     public void setExitSharedElementCallback(SharedElementCallback callback) {
1995         if (callback == null) {
1996             if (mAnimationInfo == null) {
1997                 return; // already a null callback
1998             }
1999             callback = SharedElementCallback.NULL_CALLBACK;
2000         }
2001         ensureAnimationInfo().mExitTransitionCallback = callback;
2002     }
2003 
2004     /**
2005      * Sets the Transition that will be used to move Views into the initial scene. The entering
2006      * Views will be those that are regular Views or ViewGroups that have
2007      * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
2008      * {@link android.transition.Visibility} as entering is governed by changing visibility from
2009      * {@link View#INVISIBLE} to {@link View#VISIBLE}. If <code>transition</code> is null,
2010      * entering Views will remain unaffected.
2011      *
2012      * @param transition The Transition to use to move Views into the initial Scene.
2013      * @attr ref android.R.styleable#Fragment_fragmentEnterTransition
2014      */
2015     public void setEnterTransition(Transition transition) {
2016         if (shouldChangeTransition(transition, null)) {
2017             ensureAnimationInfo().mEnterTransition = transition;
2018         }
2019     }
2020 
2021     /**
2022      * Returns the Transition that will be used to move Views into the initial scene. The entering
2023      * Views will be those that are regular Views or ViewGroups that have
2024      * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
2025      * {@link android.transition.Visibility} as entering is governed by changing visibility from
2026      * {@link View#INVISIBLE} to {@link View#VISIBLE}.
2027      *
2028      * @return the Transition to use to move Views into the initial Scene.
2029      * @attr ref android.R.styleable#Fragment_fragmentEnterTransition
2030      */
2031     public Transition getEnterTransition() {
2032         if (mAnimationInfo == null) {
2033             return null;
2034         }
2035         return mAnimationInfo.mEnterTransition;
2036     }
2037 
2038     /**
2039      * Sets the Transition that will be used to move Views out of the scene when the Fragment is
2040      * preparing to be removed, hidden, or detached because of popping the back stack. The exiting
2041      * Views will be those that are regular Views or ViewGroups that have
2042      * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
2043      * {@link android.transition.Visibility} as entering is governed by changing visibility from
2044      * {@link View#VISIBLE} to {@link View#INVISIBLE}. If <code>transition</code> is null,
2045      * entering Views will remain unaffected. If nothing is set, the default will be to
2046      * use the same value as set in {@link #setEnterTransition(android.transition.Transition)}.
2047      *
2048      * @param transition The Transition to use to move Views out of the Scene when the Fragment
2049      *                   is preparing to close.
2050      * @attr ref android.R.styleable#Fragment_fragmentExitTransition
2051      */
2052     public void setReturnTransition(Transition transition) {
2053         if (shouldChangeTransition(transition, USE_DEFAULT_TRANSITION)) {
2054             ensureAnimationInfo().mReturnTransition = transition;
2055         }
2056     }
2057 
2058     /**
2059      * Returns the Transition that will be used to move Views out of the scene when the Fragment is
2060      * preparing to be removed, hidden, or detached because of popping the back stack. The exiting
2061      * Views will be those that are regular Views or ViewGroups that have
2062      * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
2063      * {@link android.transition.Visibility} as entering is governed by changing visibility from
2064      * {@link View#VISIBLE} to {@link View#INVISIBLE}. If <code>transition</code> is null,
2065      * entering Views will remain unaffected.
2066      *
2067      * @return the Transition to use to move Views out of the Scene when the Fragment
2068      *         is preparing to close.
2069      * @attr ref android.R.styleable#Fragment_fragmentExitTransition
2070      */
2071     public Transition getReturnTransition() {
2072         if (mAnimationInfo == null) {
2073             return null;
2074         }
2075         return mAnimationInfo.mReturnTransition == USE_DEFAULT_TRANSITION ? getEnterTransition()
2076                 : mAnimationInfo.mReturnTransition;
2077     }
2078 
2079     /**
2080      * Sets the Transition that will be used to move Views out of the scene when the
2081      * fragment is removed, hidden, or detached when not popping the back stack.
2082      * The exiting Views will be those that are regular Views or ViewGroups that
2083      * have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
2084      * {@link android.transition.Visibility} as exiting is governed by changing visibility
2085      * from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null, the views will
2086      * remain unaffected.
2087      *
2088      * @param transition The Transition to use to move Views out of the Scene when the Fragment
2089      *                   is being closed not due to popping the back stack.
2090      * @attr ref android.R.styleable#Fragment_fragmentExitTransition
2091      */
2092     public void setExitTransition(Transition transition) {
2093         if (shouldChangeTransition(transition, null)) {
2094             ensureAnimationInfo().mExitTransition = transition;
2095         }
2096     }
2097 
2098     /**
2099      * Returns the Transition that will be used to move Views out of the scene when the
2100      * fragment is removed, hidden, or detached when not popping the back stack.
2101      * The exiting Views will be those that are regular Views or ViewGroups that
2102      * have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
2103      * {@link android.transition.Visibility} as exiting is governed by changing visibility
2104      * from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null, the views will
2105      * remain unaffected.
2106      *
2107      * @return the Transition to use to move Views out of the Scene when the Fragment
2108      *         is being closed not due to popping the back stack.
2109      * @attr ref android.R.styleable#Fragment_fragmentExitTransition
2110      */
2111     public Transition getExitTransition() {
2112         if (mAnimationInfo == null) {
2113             return null;
2114         }
2115         return mAnimationInfo.mExitTransition;
2116     }
2117 
2118     /**
2119      * Sets the Transition that will be used to move Views in to the scene when returning due
2120      * to popping a back stack. The entering Views will be those that are regular Views
2121      * or ViewGroups that have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions
2122      * will extend {@link android.transition.Visibility} as exiting is governed by changing
2123      * visibility from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null,
2124      * the views will remain unaffected. If nothing is set, the default will be to use the same
2125      * transition as {@link #setExitTransition(android.transition.Transition)}.
2126      *
2127      * @param transition The Transition to use to move Views into the scene when reentering from a
2128      *                   previously-started Activity.
2129      * @attr ref android.R.styleable#Fragment_fragmentReenterTransition
2130      */
2131     public void setReenterTransition(Transition transition) {
2132         if (shouldChangeTransition(transition, USE_DEFAULT_TRANSITION)) {
2133             ensureAnimationInfo().mReenterTransition = transition;
2134         }
2135     }
2136 
2137     /**
2138      * Returns the Transition that will be used to move Views in to the scene when returning due
2139      * to popping a back stack. The entering Views will be those that are regular Views
2140      * or ViewGroups that have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions
2141      * will extend {@link android.transition.Visibility} as exiting is governed by changing
2142      * visibility from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null,
2143      * the views will remain unaffected. If nothing is set, the default will be to use the same
2144      * transition as {@link #setExitTransition(android.transition.Transition)}.
2145      *
2146      * @return the Transition to use to move Views into the scene when reentering from a
2147      *                   previously-started Activity.
2148      * @attr ref android.R.styleable#Fragment_fragmentReenterTransition
2149      */
2150     public Transition getReenterTransition() {
2151         if (mAnimationInfo == null) {
2152             return null;
2153         }
2154         return mAnimationInfo.mReenterTransition == USE_DEFAULT_TRANSITION ? getExitTransition()
2155                 : mAnimationInfo.mReenterTransition;
2156     }
2157 
2158     /**
2159      * Sets the Transition that will be used for shared elements transferred into the content
2160      * Scene. Typical Transitions will affect size and location, such as
2161      * {@link android.transition.ChangeBounds}. A null
2162      * value will cause transferred shared elements to blink to the final position.
2163      *
2164      * @param transition The Transition to use for shared elements transferred into the content
2165      *                   Scene.
2166      * @attr ref android.R.styleable#Fragment_fragmentSharedElementEnterTransition
2167      */
2168     public void setSharedElementEnterTransition(Transition transition) {
2169         if (shouldChangeTransition(transition, null)) {
2170             ensureAnimationInfo().mSharedElementEnterTransition = transition;
2171         }
2172     }
2173 
2174     /**
2175      * Returns the Transition that will be used for shared elements transferred into the content
2176      * Scene. Typical Transitions will affect size and location, such as
2177      * {@link android.transition.ChangeBounds}. A null
2178      * value will cause transferred shared elements to blink to the final position.
2179      *
2180      * @return The Transition to use for shared elements transferred into the content
2181      *                   Scene.
2182      * @attr ref android.R.styleable#Fragment_fragmentSharedElementEnterTransition
2183      */
2184     public Transition getSharedElementEnterTransition() {
2185         if (mAnimationInfo == null) {
2186             return null;
2187         }
2188         return mAnimationInfo.mSharedElementEnterTransition;
2189     }
2190 
2191     /**
2192      * Sets the Transition that will be used for shared elements transferred back during a
2193      * pop of the back stack. This Transition acts in the leaving Fragment.
2194      * Typical Transitions will affect size and location, such as
2195      * {@link android.transition.ChangeBounds}. A null
2196      * value will cause transferred shared elements to blink to the final position.
2197      * If no value is set, the default will be to use the same value as
2198      * {@link #setSharedElementEnterTransition(android.transition.Transition)}.
2199      *
2200      * @param transition The Transition to use for shared elements transferred out of the content
2201      *                   Scene.
2202      * @attr ref android.R.styleable#Fragment_fragmentSharedElementReturnTransition
2203      */
2204     public void setSharedElementReturnTransition(Transition transition) {
2205         if (shouldChangeTransition(transition, USE_DEFAULT_TRANSITION)) {
2206             ensureAnimationInfo().mSharedElementReturnTransition = transition;
2207         }
2208     }
2209 
2210     /**
2211      * Return the Transition that will be used for shared elements transferred back during a
2212      * pop of the back stack. This Transition acts in the leaving Fragment.
2213      * Typical Transitions will affect size and location, such as
2214      * {@link android.transition.ChangeBounds}. A null
2215      * value will cause transferred shared elements to blink to the final position.
2216      * If no value is set, the default will be to use the same value as
2217      * {@link #setSharedElementEnterTransition(android.transition.Transition)}.
2218      *
2219      * @return The Transition to use for shared elements transferred out of the content
2220      *                   Scene.
2221      * @attr ref android.R.styleable#Fragment_fragmentSharedElementReturnTransition
2222      */
2223     public Transition getSharedElementReturnTransition() {
2224         if (mAnimationInfo == null) {
2225             return null;
2226         }
2227         return mAnimationInfo.mSharedElementReturnTransition == USE_DEFAULT_TRANSITION
2228                 ? getSharedElementEnterTransition()
2229                 : mAnimationInfo.mSharedElementReturnTransition;
2230     }
2231 
2232     /**
2233      * Sets whether the exit transition and enter transition overlap or not.
2234      * When true, the enter transition will start as soon as possible. When false, the
2235      * enter transition will wait until the exit transition completes before starting.
2236      *
2237      * @param allow true to start the enter transition when possible or false to
2238      *              wait until the exiting transition completes.
2239      * @attr ref android.R.styleable#Fragment_fragmentAllowEnterTransitionOverlap
2240      */
2241     public void setAllowEnterTransitionOverlap(boolean allow) {
2242         ensureAnimationInfo().mAllowEnterTransitionOverlap = allow;
2243     }
2244 
2245     /**
2246      * Returns whether the exit transition and enter transition overlap or not.
2247      * When true, the enter transition will start as soon as possible. When false, the
2248      * enter transition will wait until the exit transition completes before starting.
2249      *
2250      * @return true when the enter transition should start as soon as possible or false to
2251      * when it should wait until the exiting transition completes.
2252      * @attr ref android.R.styleable#Fragment_fragmentAllowEnterTransitionOverlap
2253      */
2254     public boolean getAllowEnterTransitionOverlap() {
2255         return (mAnimationInfo == null || mAnimationInfo.mAllowEnterTransitionOverlap == null)
2256                 ? true : mAnimationInfo.mAllowEnterTransitionOverlap;
2257     }
2258 
2259     /**
2260      * Sets whether the return transition and reenter transition overlap or not.
2261      * When true, the reenter transition will start as soon as possible. When false, the
2262      * reenter transition will wait until the return transition completes before starting.
2263      *
2264      * @param allow true to start the reenter transition when possible or false to wait until the
2265      *              return transition completes.
2266      * @attr ref android.R.styleable#Fragment_fragmentAllowReturnTransitionOverlap
2267      */
2268     public void setAllowReturnTransitionOverlap(boolean allow) {
2269         ensureAnimationInfo().mAllowReturnTransitionOverlap = allow;
2270     }
2271 
2272     /**
2273      * Returns whether the return transition and reenter transition overlap or not.
2274      * When true, the reenter transition will start as soon as possible. When false, the
2275      * reenter transition will wait until the return transition completes before starting.
2276      *
2277      * @return true to start the reenter transition when possible or false to wait until the
2278      *         return transition completes.
2279      * @attr ref android.R.styleable#Fragment_fragmentAllowReturnTransitionOverlap
2280      */
2281     public boolean getAllowReturnTransitionOverlap() {
2282         return (mAnimationInfo == null || mAnimationInfo.mAllowReturnTransitionOverlap == null)
2283                 ? true : mAnimationInfo.mAllowReturnTransitionOverlap;
2284     }
2285 
2286     /**
2287      * Postpone the entering Fragment transition until {@link #startPostponedEnterTransition()}
2288      * or {@link FragmentManager#executePendingTransactions()} has been called.
2289      * <p>
2290      * This method gives the Fragment the ability to delay Fragment animations
2291      * until all data is loaded. Until then, the added, shown, and
2292      * attached Fragments will be INVISIBLE and removed, hidden, and detached Fragments won't
2293      * be have their Views removed. The transaction runs when all postponed added Fragments in the
2294      * transaction have called {@link #startPostponedEnterTransition()}.
2295      * <p>
2296      * This method should be called before being added to the FragmentTransaction or
2297      * in {@link #onCreate(Bundle)}, {@link #onAttach(Context)}, or
2298      * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}}.
2299      * {@link #startPostponedEnterTransition()} must be called to allow the Fragment to
2300      * start the transitions.
2301      * <p>
2302      * When a FragmentTransaction is started that may affect a postponed FragmentTransaction,
2303      * based on which containers are in their operations, the postponed FragmentTransaction
2304      * will have its start triggered. The early triggering may result in faulty or nonexistent
2305      * animations in the postponed transaction. FragmentTransactions that operate only on
2306      * independent containers will not interfere with each other's postponement.
2307      * <p>
2308      * Calling postponeEnterTransition on Fragments with a null View will not postpone the
2309      * transition. Likewise, postponement only works if FragmentTransaction optimizations are
2310      * enabled.
2311      *
2312      * @see Activity#postponeEnterTransition()
2313      * @see FragmentTransaction#setReorderingAllowed(boolean)
2314      */
2315     public void postponeEnterTransition() {
2316         ensureAnimationInfo().mEnterTransitionPostponed = true;
2317     }
2318 
2319     /**
2320      * Begin postponed transitions after {@link #postponeEnterTransition()} was called.
2321      * If postponeEnterTransition() was called, you must call startPostponedEnterTransition()
2322      * or {@link FragmentManager#executePendingTransactions()} to complete the FragmentTransaction.
2323      * If postponement was interrupted with {@link FragmentManager#executePendingTransactions()},
2324      * before {@code startPostponedEnterTransition()}, animations may not run or may execute
2325      * improperly.
2326      *
2327      * @see Activity#startPostponedEnterTransition()
2328      */
2329     public void startPostponedEnterTransition() {
2330         if (mFragmentManager == null || mFragmentManager.mHost == null) {
2331                 ensureAnimationInfo().mEnterTransitionPostponed = false;
2332         } else if (Looper.myLooper() != mFragmentManager.mHost.getHandler().getLooper()) {
2333             mFragmentManager.mHost.getHandler().
2334                     postAtFrontOfQueue(this::callStartTransitionListener);
2335         } else {
2336             callStartTransitionListener();
2337         }
2338     }
2339 
2340     /**
2341      * Calls the start transition listener. This must be called on the UI thread.
2342      */
2343     private void callStartTransitionListener() {
2344         final OnStartEnterTransitionListener listener;
2345         if (mAnimationInfo == null) {
2346             listener = null;
2347         } else {
2348             mAnimationInfo.mEnterTransitionPostponed = false;
2349             listener = mAnimationInfo.mStartEnterTransitionListener;
2350             mAnimationInfo.mStartEnterTransitionListener = null;
2351         }
2352         if (listener != null) {
2353             listener.onStartEnterTransition();
2354         }
2355     }
2356 
2357     /**
2358      * Returns true if mAnimationInfo is not null or the transition differs from the default value.
2359      * This is broken out to ensure mAnimationInfo is properly locked when checking.
2360      */
2361     private boolean shouldChangeTransition(Transition transition, Transition defaultValue) {
2362         if (transition == defaultValue) {
2363             return mAnimationInfo != null;
2364         }
2365         return true;
2366     }
2367 
2368     /**
2369      * Print the Fragments's state into the given stream.
2370      *
2371      * @param prefix Text to print at the front of each line.
2372      * @param fd The raw file descriptor that the dump is being sent to.
2373      * @param writer The PrintWriter to which you should dump your state.  This will be
2374      * closed for you after you return.
2375      * @param args additional arguments to the dump request.
2376      */
2377     public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
2378         writer.print(prefix); writer.print("mFragmentId=#");
2379         writer.print(Integer.toHexString(mFragmentId));
2380         writer.print(" mContainerId=#");
2381         writer.print(Integer.toHexString(mContainerId));
2382         writer.print(" mTag="); writer.println(mTag);
2383         writer.print(prefix); writer.print("mState="); writer.print(mState);
2384         writer.print(" mIndex="); writer.print(mIndex);
2385         writer.print(" mWho="); writer.print(mWho);
2386         writer.print(" mBackStackNesting="); writer.println(mBackStackNesting);
2387         writer.print(prefix); writer.print("mAdded="); writer.print(mAdded);
2388         writer.print(" mRemoving="); writer.print(mRemoving);
2389         writer.print(" mFromLayout="); writer.print(mFromLayout);
2390         writer.print(" mInLayout="); writer.println(mInLayout);
2391         writer.print(prefix); writer.print("mHidden="); writer.print(mHidden);
2392         writer.print(" mDetached="); writer.print(mDetached);
2393         writer.print(" mMenuVisible="); writer.print(mMenuVisible);
2394         writer.print(" mHasMenu="); writer.println(mHasMenu);
2395         writer.print(prefix); writer.print("mRetainInstance="); writer.print(mRetainInstance);
2396         writer.print(" mRetaining="); writer.print(mRetaining);
2397         writer.print(" mUserVisibleHint="); writer.println(mUserVisibleHint);
2398         if (mFragmentManager != null) {
2399             writer.print(prefix); writer.print("mFragmentManager=");
2400             writer.println(mFragmentManager);
2401         }
2402         if (mHost != null) {
2403             writer.print(prefix); writer.print("mHost=");
2404             writer.println(mHost);
2405         }
2406         if (mParentFragment != null) {
2407             writer.print(prefix); writer.print("mParentFragment=");
2408             writer.println(mParentFragment);
2409         }
2410         if (mArguments != null) {
2411             writer.print(prefix); writer.print("mArguments="); writer.println(mArguments);
2412         }
2413         if (mSavedFragmentState != null) {
2414             writer.print(prefix); writer.print("mSavedFragmentState=");
2415             writer.println(mSavedFragmentState);
2416         }
2417         if (mSavedViewState != null) {
2418             writer.print(prefix); writer.print("mSavedViewState=");
2419             writer.println(mSavedViewState);
2420         }
2421         if (mTarget != null) {
2422             writer.print(prefix); writer.print("mTarget="); writer.print(mTarget);
2423             writer.print(" mTargetRequestCode=");
2424             writer.println(mTargetRequestCode);
2425         }
2426         if (getNextAnim() != 0) {
2427             writer.print(prefix); writer.print("mNextAnim="); writer.println(getNextAnim());
2428         }
2429         if (mContainer != null) {
2430             writer.print(prefix); writer.print("mContainer="); writer.println(mContainer);
2431         }
2432         if (mView != null) {
2433             writer.print(prefix); writer.print("mView="); writer.println(mView);
2434         }
2435         if (getAnimatingAway() != null) {
2436             writer.print(prefix); writer.print("mAnimatingAway=");
2437             writer.println(getAnimatingAway());
2438             writer.print(prefix); writer.print("mStateAfterAnimating=");
2439             writer.println(getStateAfterAnimating());
2440         }
2441         if (mLoaderManager != null) {
2442             writer.print(prefix); writer.println("Loader Manager:");
2443             mLoaderManager.dump(prefix + "  ", fd, writer, args);
2444         }
2445         if (mChildFragmentManager != null) {
2446             writer.print(prefix); writer.println("Child " + mChildFragmentManager + ":");
2447             mChildFragmentManager.dump(prefix + "  ", fd, writer, args);
2448         }
2449     }
2450 
2451     Fragment findFragmentByWho(String who) {
2452         if (who.equals(mWho)) {
2453             return this;
2454         }
2455         if (mChildFragmentManager != null) {
2456             return mChildFragmentManager.findFragmentByWho(who);
2457         }
2458         return null;
2459     }
2460 
2461     void instantiateChildFragmentManager() {
2462         mChildFragmentManager = new FragmentManagerImpl();
2463         mChildFragmentManager.attachController(mHost, new FragmentContainer() {
2464             @Override
2465             @Nullable
2466             public <T extends View> T onFindViewById(int id) {
2467                 if (mView == null) {
2468                     throw new IllegalStateException("Fragment does not have a view");
2469                 }
2470                 return mView.findViewById(id);
2471             }
2472 
2473             @Override
2474             public boolean onHasView() {
2475                 return (mView != null);
2476             }
2477         }, this);
2478     }
2479 
2480     void performCreate(Bundle savedInstanceState) {
2481         if (mChildFragmentManager != null) {
2482             mChildFragmentManager.noteStateNotSaved();
2483         }
2484         mState = CREATED;
2485         mCalled = false;
2486         onCreate(savedInstanceState);
2487         mIsCreated = true;
2488         if (!mCalled) {
2489             throw new SuperNotCalledException("Fragment " + this
2490                     + " did not call through to super.onCreate()");
2491         }
2492         final Context context = getContext();
2493         final int version = context != null ? context.getApplicationInfo().targetSdkVersion : 0;
2494         if (version < Build.VERSION_CODES.N) {
2495             restoreChildFragmentState(savedInstanceState, false);
2496         }
2497     }
2498 
2499     View performCreateView(LayoutInflater inflater, ViewGroup container,
2500             Bundle savedInstanceState) {
2501         if (mChildFragmentManager != null) {
2502             mChildFragmentManager.noteStateNotSaved();
2503         }
2504         mPerformedCreateView = true;
2505         return onCreateView(inflater, container, savedInstanceState);
2506     }
2507 
2508     void performActivityCreated(Bundle savedInstanceState) {
2509         if (mChildFragmentManager != null) {
2510             mChildFragmentManager.noteStateNotSaved();
2511         }
2512         mState = ACTIVITY_CREATED;
2513         mCalled = false;
2514         onActivityCreated(savedInstanceState);
2515         if (!mCalled) {
2516             throw new SuperNotCalledException("Fragment " + this
2517                     + " did not call through to super.onActivityCreated()");
2518         }
2519         if (mChildFragmentManager != null) {
2520             mChildFragmentManager.dispatchActivityCreated();
2521         }
2522     }
2523 
2524     void performStart() {
2525         if (mChildFragmentManager != null) {
2526             mChildFragmentManager.noteStateNotSaved();
2527             mChildFragmentManager.execPendingActions();
2528         }
2529         mState = STARTED;
2530         mCalled = false;
2531         onStart();
2532         if (!mCalled) {
2533             throw new SuperNotCalledException("Fragment " + this
2534                     + " did not call through to super.onStart()");
2535         }
2536         if (mChildFragmentManager != null) {
2537             mChildFragmentManager.dispatchStart();
2538         }
2539         if (mLoaderManager != null) {
2540             mLoaderManager.doReportStart();
2541         }
2542     }
2543 
2544     void performResume() {
2545         if (mChildFragmentManager != null) {
2546             mChildFragmentManager.noteStateNotSaved();
2547             mChildFragmentManager.execPendingActions();
2548         }
2549         mState = RESUMED;
2550         mCalled = false;
2551         onResume();
2552         if (!mCalled) {
2553             throw new SuperNotCalledException("Fragment " + this
2554                     + " did not call through to super.onResume()");
2555         }
2556         if (mChildFragmentManager != null) {
2557             mChildFragmentManager.dispatchResume();
2558             mChildFragmentManager.execPendingActions();
2559         }
2560     }
2561 
2562     void noteStateNotSaved() {
2563         if (mChildFragmentManager != null) {
2564             mChildFragmentManager.noteStateNotSaved();
2565         }
2566     }
2567 
2568     @Deprecated
2569     void performMultiWindowModeChanged(boolean isInMultiWindowMode) {
2570         onMultiWindowModeChanged(isInMultiWindowMode);
2571         if (mChildFragmentManager != null) {
2572             mChildFragmentManager.dispatchMultiWindowModeChanged(isInMultiWindowMode);
2573         }
2574     }
2575 
2576     void performMultiWindowModeChanged(boolean isInMultiWindowMode, Configuration newConfig) {
2577         onMultiWindowModeChanged(isInMultiWindowMode, newConfig);
2578         if (mChildFragmentManager != null) {
2579             mChildFragmentManager.dispatchMultiWindowModeChanged(isInMultiWindowMode, newConfig);
2580         }
2581     }
2582 
2583     @Deprecated
2584     void performPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
2585         onPictureInPictureModeChanged(isInPictureInPictureMode);
2586         if (mChildFragmentManager != null) {
2587             mChildFragmentManager.dispatchPictureInPictureModeChanged(isInPictureInPictureMode);
2588         }
2589     }
2590 
2591     void performPictureInPictureModeChanged(boolean isInPictureInPictureMode,
2592             Configuration newConfig) {
2593         onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
2594         if (mChildFragmentManager != null) {
2595             mChildFragmentManager.dispatchPictureInPictureModeChanged(isInPictureInPictureMode,
2596                     newConfig);
2597         }
2598     }
2599 
2600     void performConfigurationChanged(Configuration newConfig) {
2601         onConfigurationChanged(newConfig);
2602         if (mChildFragmentManager != null) {
2603             mChildFragmentManager.dispatchConfigurationChanged(newConfig);
2604         }
2605     }
2606 
2607     void performLowMemory() {
2608         onLowMemory();
2609         if (mChildFragmentManager != null) {
2610             mChildFragmentManager.dispatchLowMemory();
2611         }
2612     }
2613 
2614     void performTrimMemory(int level) {
2615         onTrimMemory(level);
2616         if (mChildFragmentManager != null) {
2617             mChildFragmentManager.dispatchTrimMemory(level);
2618         }
2619     }
2620 
2621     boolean performCreateOptionsMenu(Menu menu, MenuInflater inflater) {
2622         boolean show = false;
2623         if (!mHidden) {
2624             if (mHasMenu && mMenuVisible) {
2625                 show = true;
2626                 onCreateOptionsMenu(menu, inflater);
2627             }
2628             if (mChildFragmentManager != null) {
2629                 show |= mChildFragmentManager.dispatchCreateOptionsMenu(menu, inflater);
2630             }
2631         }
2632         return show;
2633     }
2634 
2635     boolean performPrepareOptionsMenu(Menu menu) {
2636         boolean show = false;
2637         if (!mHidden) {
2638             if (mHasMenu && mMenuVisible) {
2639                 show = true;
2640                 onPrepareOptionsMenu(menu);
2641             }
2642             if (mChildFragmentManager != null) {
2643                 show |= mChildFragmentManager.dispatchPrepareOptionsMenu(menu);
2644             }
2645         }
2646         return show;
2647     }
2648 
2649     boolean performOptionsItemSelected(MenuItem item) {
2650         if (!mHidden) {
2651             if (mHasMenu && mMenuVisible) {
2652                 if (onOptionsItemSelected(item)) {
2653                     return true;
2654                 }
2655             }
2656             if (mChildFragmentManager != null) {
2657                 if (mChildFragmentManager.dispatchOptionsItemSelected(item)) {
2658                     return true;
2659                 }
2660             }
2661         }
2662         return false;
2663     }
2664 
2665     boolean performContextItemSelected(MenuItem item) {
2666         if (!mHidden) {
2667             if (onContextItemSelected(item)) {
2668                 return true;
2669             }
2670             if (mChildFragmentManager != null) {
2671                 if (mChildFragmentManager.dispatchContextItemSelected(item)) {
2672                     return true;
2673                 }
2674             }
2675         }
2676         return false;
2677     }
2678 
2679     void performOptionsMenuClosed(Menu menu) {
2680         if (!mHidden) {
2681             if (mHasMenu && mMenuVisible) {
2682                 onOptionsMenuClosed(menu);
2683             }
2684             if (mChildFragmentManager != null) {
2685                 mChildFragmentManager.dispatchOptionsMenuClosed(menu);
2686             }
2687         }
2688     }
2689 
2690     void performSaveInstanceState(Bundle outState) {
2691         onSaveInstanceState(outState);
2692         if (mChildFragmentManager != null) {
2693             Parcelable p = mChildFragmentManager.saveAllState();
2694             if (p != null) {
2695                 outState.putParcelable(Activity.FRAGMENTS_TAG, p);
2696             }
2697         }
2698     }
2699 
2700     void performPause() {
2701         if (mChildFragmentManager != null) {
2702             mChildFragmentManager.dispatchPause();
2703         }
2704         mState = STARTED;
2705         mCalled = false;
2706         onPause();
2707         if (!mCalled) {
2708             throw new SuperNotCalledException("Fragment " + this
2709                     + " did not call through to super.onPause()");
2710         }
2711     }
2712 
2713     void performStop() {
2714         if (mChildFragmentManager != null) {
2715             mChildFragmentManager.dispatchStop();
2716         }
2717         mState = STOPPED;
2718         mCalled = false;
2719         onStop();
2720         if (!mCalled) {
2721             throw new SuperNotCalledException("Fragment " + this
2722                     + " did not call through to super.onStop()");
2723         }
2724 
2725         if (mLoadersStarted) {
2726             mLoadersStarted = false;
2727             if (!mCheckedForLoaderManager) {
2728                 mCheckedForLoaderManager = true;
2729                 mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, false);
2730             }
2731             if (mLoaderManager != null) {
2732                 if (mHost.getRetainLoaders()) {
2733                     mLoaderManager.doRetain();
2734                 } else {
2735                     mLoaderManager.doStop();
2736                 }
2737             }
2738         }
2739     }
2740 
2741     void performDestroyView() {
2742         if (mChildFragmentManager != null) {
2743             mChildFragmentManager.dispatchDestroyView();
2744         }
2745         mState = CREATED;
2746         mCalled = false;
2747         onDestroyView();
2748         if (!mCalled) {
2749             throw new SuperNotCalledException("Fragment " + this
2750                     + " did not call through to super.onDestroyView()");
2751         }
2752         if (mLoaderManager != null) {
2753             mLoaderManager.doReportNextStart();
2754         }
2755         mPerformedCreateView = false;
2756     }
2757 
2758     void performDestroy() {
2759         if (mChildFragmentManager != null) {
2760             mChildFragmentManager.dispatchDestroy();
2761         }
2762         mState = INITIALIZING;
2763         mCalled = false;
2764         mIsCreated = false;
2765         onDestroy();
2766         if (!mCalled) {
2767             throw new SuperNotCalledException("Fragment " + this
2768                     + " did not call through to super.onDestroy()");
2769         }
2770         mChildFragmentManager = null;
2771     }
2772 
2773     void performDetach() {
2774         mCalled = false;
2775         onDetach();
2776         mLayoutInflater = null;
2777         if (!mCalled) {
2778             throw new SuperNotCalledException("Fragment " + this
2779                     + " did not call through to super.onDetach()");
2780         }
2781 
2782         // Destroy the child FragmentManager if we still have it here.
2783         // We won't unless we're retaining our instance and if we do,
2784         // our child FragmentManager instance state will have already been saved.
2785         if (mChildFragmentManager != null) {
2786             if (!mRetaining) {
2787                 throw new IllegalStateException("Child FragmentManager of " + this + " was not "
2788                         + " destroyed and this fragment is not retaining instance");
2789             }
2790             mChildFragmentManager.dispatchDestroy();
2791             mChildFragmentManager = null;
2792         }
2793     }
2794 
2795     void setOnStartEnterTransitionListener(OnStartEnterTransitionListener listener) {
2796         ensureAnimationInfo();
2797         if (listener == mAnimationInfo.mStartEnterTransitionListener) {
2798             return;
2799         }
2800         if (listener != null && mAnimationInfo.mStartEnterTransitionListener != null) {
2801             throw new IllegalStateException("Trying to set a replacement " +
2802                     "startPostponedEnterTransition on " + this);
2803         }
2804         if (mAnimationInfo.mEnterTransitionPostponed) {
2805             mAnimationInfo.mStartEnterTransitionListener = listener;
2806         }
2807         if (listener != null) {
2808             listener.startListening();
2809         }
2810     }
2811 
2812     private static Transition loadTransition(Context context, TypedArray typedArray,
2813             Transition currentValue, Transition defaultValue, int id) {
2814         if (currentValue != defaultValue) {
2815             return currentValue;
2816         }
2817         int transitionId = typedArray.getResourceId(id, 0);
2818         Transition transition = defaultValue;
2819         if (transitionId != 0 && transitionId != com.android.internal.R.transition.no_transition) {
2820             TransitionInflater inflater = TransitionInflater.from(context);
2821             transition = inflater.inflateTransition(transitionId);
2822             if (transition instanceof TransitionSet &&
2823                     ((TransitionSet)transition).getTransitionCount() == 0) {
2824                 transition = null;
2825             }
2826         }
2827         return transition;
2828     }
2829 
2830     private AnimationInfo ensureAnimationInfo() {
2831         if (mAnimationInfo == null) {
2832             mAnimationInfo = new AnimationInfo();
2833         }
2834         return mAnimationInfo;
2835     }
2836 
2837     int getNextAnim() {
2838         if (mAnimationInfo == null) {
2839             return 0;
2840         }
2841         return mAnimationInfo.mNextAnim;
2842     }
2843 
2844     void setNextAnim(int animResourceId) {
2845         if (mAnimationInfo == null && animResourceId == 0) {
2846             return; // no change!
2847         }
2848         ensureAnimationInfo().mNextAnim = animResourceId;
2849     }
2850 
2851     int getNextTransition() {
2852         if (mAnimationInfo == null) {
2853             return 0;
2854         }
2855         return mAnimationInfo.mNextTransition;
2856     }
2857 
2858     void setNextTransition(int nextTransition, int nextTransitionStyle) {
2859         if (mAnimationInfo == null && nextTransition == 0 && nextTransitionStyle == 0) {
2860             return; // no change!
2861         }
2862         ensureAnimationInfo();
2863         mAnimationInfo.mNextTransition = nextTransition;
2864         mAnimationInfo.mNextTransitionStyle = nextTransitionStyle;
2865     }
2866 
2867     int getNextTransitionStyle() {
2868         if (mAnimationInfo == null) {
2869             return 0;
2870         }
2871         return mAnimationInfo.mNextTransitionStyle;
2872     }
2873 
2874     SharedElementCallback getEnterTransitionCallback() {
2875         if (mAnimationInfo == null) {
2876             return SharedElementCallback.NULL_CALLBACK;
2877         }
2878         return mAnimationInfo.mEnterTransitionCallback;
2879     }
2880 
2881     SharedElementCallback getExitTransitionCallback() {
2882         if (mAnimationInfo == null) {
2883             return SharedElementCallback.NULL_CALLBACK;
2884         }
2885         return mAnimationInfo.mExitTransitionCallback;
2886     }
2887 
2888     Animator getAnimatingAway() {
2889         if (mAnimationInfo == null) {
2890             return null;
2891         }
2892         return mAnimationInfo.mAnimatingAway;
2893     }
2894 
2895     void setAnimatingAway(Animator animator) {
2896         ensureAnimationInfo().mAnimatingAway = animator;
2897     }
2898 
2899     int getStateAfterAnimating() {
2900         if (mAnimationInfo == null) {
2901             return 0;
2902         }
2903         return mAnimationInfo.mStateAfterAnimating;
2904     }
2905 
2906     void setStateAfterAnimating(int state) {
2907         ensureAnimationInfo().mStateAfterAnimating = state;
2908     }
2909 
2910     boolean isPostponed() {
2911         if (mAnimationInfo == null) {
2912             return false;
2913         }
2914         return mAnimationInfo.mEnterTransitionPostponed;
2915     }
2916 
2917     boolean isHideReplaced() {
2918         if (mAnimationInfo == null) {
2919             return false;
2920         }
2921         return mAnimationInfo.mIsHideReplaced;
2922     }
2923 
2924     void setHideReplaced(boolean replaced) {
2925         ensureAnimationInfo().mIsHideReplaced = replaced;
2926     }
2927 
2928     /**
2929      * Used internally to be notified when {@link #startPostponedEnterTransition()} has
2930      * been called. This listener will only be called once and then be removed from the
2931      * listeners.
2932      */
2933     interface OnStartEnterTransitionListener {
2934         void onStartEnterTransition();
2935         void startListening();
2936     }
2937 
2938     /**
2939      * Contains all the animation and transition information for a fragment. This will only
2940      * be instantiated for Fragments that have Views.
2941      */
2942     static class AnimationInfo {
2943         // Non-null if the fragment's view hierarchy is currently animating away,
2944         // meaning we need to wait a bit on completely destroying it.  This is the
2945         // animation that is running.
2946         Animator mAnimatingAway;
2947 
2948         // If mAnimatingAway != null, this is the state we should move to once the
2949         // animation is done.
2950         int mStateAfterAnimating;
2951 
2952         // If app has requested a specific animation, this is the one to use.
2953         int mNextAnim;
2954 
2955         // If app has requested a specific transition, this is the one to use.
2956         int mNextTransition;
2957 
2958         // If app has requested a specific transition style, this is the one to use.
2959         int mNextTransitionStyle;
2960 
2961         private Transition mEnterTransition = null;
2962         private Transition mReturnTransition = USE_DEFAULT_TRANSITION;
2963         private Transition mExitTransition = null;
2964         private Transition mReenterTransition = USE_DEFAULT_TRANSITION;
2965         private Transition mSharedElementEnterTransition = null;
2966         private Transition mSharedElementReturnTransition = USE_DEFAULT_TRANSITION;
2967         private Boolean mAllowReturnTransitionOverlap;
2968         private Boolean mAllowEnterTransitionOverlap;
2969 
2970         SharedElementCallback mEnterTransitionCallback = SharedElementCallback.NULL_CALLBACK;
2971         SharedElementCallback mExitTransitionCallback = SharedElementCallback.NULL_CALLBACK;
2972 
2973         // True when postponeEnterTransition has been called and startPostponeEnterTransition
2974         // hasn't been called yet.
2975         boolean mEnterTransitionPostponed;
2976 
2977         // Listener to wait for startPostponeEnterTransition. After being called, it will
2978         // be set to null
2979         OnStartEnterTransitionListener mStartEnterTransitionListener;
2980 
2981         // True if the View was hidden, but the transition is handling the hide
2982         boolean mIsHideReplaced;
2983     }
2984 }
2985