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