Fragment.java revision 0621742d3c9e691e4615da924db69333e371f3f7
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.Handler;
35import android.os.Looper;
36import android.os.Parcel;
37import android.os.Parcelable;
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.  This can only
718     * be called before the fragment has been attached to its activity; that
719     * is, you should call it immediately after constructing the fragment.  The
720     * arguments supplied here will be retained across fragment destroy and
721     * creation.
722     */
723    public void setArguments(Bundle args) {
724        if (mIndex >= 0) {
725            throw new IllegalStateException("Fragment already active");
726        }
727        mArguments = args;
728    }
729
730    /**
731     * Return the arguments supplied to {@link #setArguments}, if any.
732     */
733    final public Bundle getArguments() {
734        return mArguments;
735    }
736
737    /**
738     * Set the initial saved state that this Fragment should restore itself
739     * from when first being constructed, as returned by
740     * {@link FragmentManager#saveFragmentInstanceState(Fragment)
741     * FragmentManager.saveFragmentInstanceState}.
742     *
743     * @param state The state the fragment should be restored from.
744     */
745    public void setInitialSavedState(SavedState state) {
746        if (mIndex >= 0) {
747            throw new IllegalStateException("Fragment already active");
748        }
749        mSavedFragmentState = state != null && state.mState != null
750                ? state.mState : null;
751    }
752
753    /**
754     * Optional target for this fragment.  This may be used, for example,
755     * if this fragment is being started by another, and when done wants to
756     * give a result back to the first.  The target set here is retained
757     * across instances via {@link FragmentManager#putFragment
758     * FragmentManager.putFragment()}.
759     *
760     * @param fragment The fragment that is the target of this one.
761     * @param requestCode Optional request code, for convenience if you
762     * are going to call back with {@link #onActivityResult(int, int, Intent)}.
763     */
764    public void setTargetFragment(Fragment fragment, int requestCode) {
765        // Don't allow a caller to set a target fragment in another FragmentManager,
766        // but there's a snag: people do set target fragments before fragments get added.
767        // We'll have the FragmentManager check that for validity when we move
768        // the fragments to a valid state.
769        final FragmentManager mine = getFragmentManager();
770        final FragmentManager theirs = fragment != null ? fragment.getFragmentManager() : null;
771        if (mine != null && theirs != null && mine != theirs) {
772            throw new IllegalArgumentException("Fragment " + fragment
773                    + " must share the same FragmentManager to be set as a target fragment");
774        }
775
776        // Don't let someone create a cycle.
777        for (Fragment check = fragment; check != null; check = check.getTargetFragment()) {
778            if (check == this) {
779                throw new IllegalArgumentException("Setting " + fragment + " as the target of "
780                        + this + " would create a target cycle");
781            }
782        }
783        mTarget = fragment;
784        mTargetRequestCode = requestCode;
785    }
786
787    /**
788     * Return the target fragment set by {@link #setTargetFragment}.
789     */
790    final public Fragment getTargetFragment() {
791        return mTarget;
792    }
793
794    /**
795     * Return the target request code set by {@link #setTargetFragment}.
796     */
797    final public int getTargetRequestCode() {
798        return mTargetRequestCode;
799    }
800
801    /**
802     * Return the {@link Context} this fragment is currently associated with.
803     */
804    public Context getContext() {
805        return mHost == null ? null : mHost.getContext();
806    }
807
808    /**
809     * Return the Activity this fragment is currently associated with.
810     */
811    final public Activity getActivity() {
812        return mHost == null ? null : mHost.getActivity();
813    }
814
815    /**
816     * Return the host object of this fragment. May return {@code null} if the fragment
817     * isn't currently being hosted.
818     */
819    @Nullable
820    final public Object getHost() {
821        return mHost == null ? null : mHost.onGetHost();
822    }
823
824    /**
825     * Return <code>getActivity().getResources()</code>.
826     */
827    final public Resources getResources() {
828        if (mHost == null) {
829            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
830        }
831        return mHost.getContext().getResources();
832    }
833
834    /**
835     * Return a localized, styled CharSequence from the application's package's
836     * default string table.
837     *
838     * @param resId Resource id for the CharSequence text
839     */
840    public final CharSequence getText(@StringRes int resId) {
841        return getResources().getText(resId);
842    }
843
844    /**
845     * Return a localized string from the application's package's
846     * default string table.
847     *
848     * @param resId Resource id for the string
849     */
850    public final String getString(@StringRes int resId) {
851        return getResources().getString(resId);
852    }
853
854    /**
855     * Return a localized formatted string from the application's package's
856     * default string table, substituting the format arguments as defined in
857     * {@link java.util.Formatter} and {@link java.lang.String#format}.
858     *
859     * @param resId Resource id for the format string
860     * @param formatArgs The format arguments that will be used for substitution.
861     */
862
863    public final String getString(@StringRes int resId, Object... formatArgs) {
864        return getResources().getString(resId, formatArgs);
865    }
866
867    /**
868     * Return the FragmentManager for interacting with fragments associated
869     * with this fragment's activity.  Note that this will be non-null slightly
870     * before {@link #getActivity()}, during the time from when the fragment is
871     * placed in a {@link FragmentTransaction} until it is committed and
872     * attached to its activity.
873     *
874     * <p>If this Fragment is a child of another Fragment, the FragmentManager
875     * returned here will be the parent's {@link #getChildFragmentManager()}.
876     */
877    final public FragmentManager getFragmentManager() {
878        return mFragmentManager;
879    }
880
881    /**
882     * Return a private FragmentManager for placing and managing Fragments
883     * inside of this Fragment.
884     */
885    final public FragmentManager getChildFragmentManager() {
886        if (mChildFragmentManager == null) {
887            instantiateChildFragmentManager();
888            if (mState >= RESUMED) {
889                mChildFragmentManager.dispatchResume();
890            } else if (mState >= STARTED) {
891                mChildFragmentManager.dispatchStart();
892            } else if (mState >= ACTIVITY_CREATED) {
893                mChildFragmentManager.dispatchActivityCreated();
894            } else if (mState >= CREATED) {
895                mChildFragmentManager.dispatchCreate();
896            }
897        }
898        return mChildFragmentManager;
899    }
900
901    /**
902     * Returns the parent Fragment containing this Fragment.  If this Fragment
903     * is attached directly to an Activity, returns null.
904     */
905    final public Fragment getParentFragment() {
906        return mParentFragment;
907    }
908
909    /**
910     * Return true if the fragment is currently added to its activity.
911     */
912    final public boolean isAdded() {
913        return mHost != null && mAdded;
914    }
915
916    /**
917     * Return true if the fragment has been explicitly detached from the UI.
918     * That is, {@link FragmentTransaction#detach(Fragment)
919     * FragmentTransaction.detach(Fragment)} has been used on it.
920     */
921    final public boolean isDetached() {
922        return mDetached;
923    }
924
925    /**
926     * Return true if this fragment is currently being removed from its
927     * activity.  This is  <em>not</em> whether its activity is finishing, but
928     * rather whether it is in the process of being removed from its activity.
929     */
930    final public boolean isRemoving() {
931        return mRemoving;
932    }
933
934    /**
935     * Return true if the layout is included as part of an activity view
936     * hierarchy via the &lt;fragment&gt; tag.  This will always be true when
937     * fragments are created through the &lt;fragment&gt; tag, <em>except</em>
938     * in the case where an old fragment is restored from a previous state and
939     * it does not appear in the layout of the current state.
940     */
941    final public boolean isInLayout() {
942        return mInLayout;
943    }
944
945    /**
946     * Return true if the fragment is in the resumed state.  This is true
947     * for the duration of {@link #onResume()} and {@link #onPause()} as well.
948     */
949    final public boolean isResumed() {
950        return mState >= RESUMED;
951    }
952
953    /**
954     * Return true if the fragment is currently visible to the user.  This means
955     * it: (1) has been added, (2) has its view attached to the window, and
956     * (3) is not hidden.
957     */
958    final public boolean isVisible() {
959        return isAdded() && !isHidden() && mView != null
960                && mView.getWindowToken() != null && mView.getVisibility() == View.VISIBLE;
961    }
962
963    /**
964     * Return true if the fragment has been hidden.  By default fragments
965     * are shown.  You can find out about changes to this state with
966     * {@link #onHiddenChanged}.  Note that the hidden state is orthogonal
967     * to other states -- that is, to be visible to the user, a fragment
968     * must be both started and not hidden.
969     */
970    final public boolean isHidden() {
971        return mHidden;
972    }
973
974    /**
975     * Called when the hidden state (as returned by {@link #isHidden()} of
976     * the fragment has changed.  Fragments start out not hidden; this will
977     * be called whenever the fragment changes state from that.
978     * @param hidden True if the fragment is now hidden, false otherwise.
979     */
980    public void onHiddenChanged(boolean hidden) {
981    }
982
983    /**
984     * Control whether a fragment instance is retained across Activity
985     * re-creation (such as from a configuration change).  This can only
986     * be used with fragments not in the back stack.  If set, the fragment
987     * lifecycle will be slightly different when an activity is recreated:
988     * <ul>
989     * <li> {@link #onDestroy()} will not be called (but {@link #onDetach()} still
990     * will be, because the fragment is being detached from its current activity).
991     * <li> {@link #onCreate(Bundle)} will not be called since the fragment
992     * is not being re-created.
993     * <li> {@link #onAttach(Activity)} and {@link #onActivityCreated(Bundle)} <b>will</b>
994     * still be called.
995     * </ul>
996     */
997    public void setRetainInstance(boolean retain) {
998        mRetainInstance = retain;
999    }
1000
1001    final public boolean getRetainInstance() {
1002        return mRetainInstance;
1003    }
1004
1005    /**
1006     * Report that this fragment would like to participate in populating
1007     * the options menu by receiving a call to {@link #onCreateOptionsMenu}
1008     * and related methods.
1009     *
1010     * @param hasMenu If true, the fragment has menu items to contribute.
1011     */
1012    public void setHasOptionsMenu(boolean hasMenu) {
1013        if (mHasMenu != hasMenu) {
1014            mHasMenu = hasMenu;
1015            if (isAdded() && !isHidden()) {
1016                mFragmentManager.invalidateOptionsMenu();
1017            }
1018        }
1019    }
1020
1021    /**
1022     * Set a hint for whether this fragment's menu should be visible.  This
1023     * is useful if you know that a fragment has been placed in your view
1024     * hierarchy so that the user can not currently seen it, so any menu items
1025     * it has should also not be shown.
1026     *
1027     * @param menuVisible The default is true, meaning the fragment's menu will
1028     * be shown as usual.  If false, the user will not see the menu.
1029     */
1030    public void setMenuVisibility(boolean menuVisible) {
1031        if (mMenuVisible != menuVisible) {
1032            mMenuVisible = menuVisible;
1033            if (mHasMenu && isAdded() && !isHidden()) {
1034                mFragmentManager.invalidateOptionsMenu();
1035            }
1036        }
1037    }
1038
1039    /**
1040     * Set a hint to the system about whether this fragment's UI is currently visible
1041     * to the user. This hint defaults to true and is persistent across fragment instance
1042     * state save and restore.
1043     *
1044     * <p>An app may set this to false to indicate that the fragment's UI is
1045     * scrolled out of visibility or is otherwise not directly visible to the user.
1046     * This may be used by the system to prioritize operations such as fragment lifecycle updates
1047     * or loader ordering behavior.</p>
1048     *
1049     * <p><strong>Note:</strong> This method may be called outside of the fragment lifecycle
1050     * and thus has no ordering guarantees with regard to fragment lifecycle method calls.</p>
1051     *
1052     * <p><strong>Note:</strong> Prior to Android N there was a platform bug that could cause
1053     * <code>setUserVisibleHint</code> to bring a fragment up to the started state before its
1054     * <code>FragmentTransaction</code> had been committed. As some apps relied on this behavior,
1055     * it is preserved for apps that declare a <code>targetSdkVersion</code> of 23 or lower.</p>
1056     *
1057     * @param isVisibleToUser true if this fragment's UI is currently visible to the user (default),
1058     *                        false if it is not.
1059     */
1060    public void setUserVisibleHint(boolean isVisibleToUser) {
1061        // Prior to Android N we were simply checking if this fragment had a FragmentManager
1062        // set before we would trigger a deferred start. Unfortunately this also gets set before
1063        // a fragment transaction is committed, so if setUserVisibleHint was called before a
1064        // transaction commit, we would start the fragment way too early. FragmentPagerAdapter
1065        // triggers this situation.
1066        // Unfortunately some apps relied on this timing in overrides of setUserVisibleHint
1067        // on their own fragments, and expected, however erroneously, that after a call to
1068        // super.setUserVisibleHint their onStart methods had been run.
1069        // We preserve this behavior for apps targeting old platform versions below.
1070        boolean useBrokenAddedCheck = false;
1071        Context context = getContext();
1072        if (mFragmentManager != null && mFragmentManager.mHost != null) {
1073            context = mFragmentManager.mHost.getContext();
1074        }
1075        if (context != null) {
1076            useBrokenAddedCheck = context.getApplicationInfo().targetSdkVersion <= VERSION_CODES.M;
1077        }
1078
1079        final boolean performDeferredStart;
1080        if (useBrokenAddedCheck) {
1081            performDeferredStart = !mUserVisibleHint && isVisibleToUser && mState < STARTED
1082                    && mFragmentManager != null;
1083        } else {
1084            performDeferredStart = !mUserVisibleHint && isVisibleToUser && mState < STARTED
1085                    && mFragmentManager != null && isAdded();
1086        }
1087
1088        if (performDeferredStart) {
1089            mFragmentManager.performPendingDeferredStart(this);
1090        }
1091
1092        mUserVisibleHint = isVisibleToUser;
1093        mDeferStart = mState < STARTED && !isVisibleToUser;
1094    }
1095
1096    /**
1097     * @return The current value of the user-visible hint on this fragment.
1098     * @see #setUserVisibleHint(boolean)
1099     */
1100    public boolean getUserVisibleHint() {
1101        return mUserVisibleHint;
1102    }
1103
1104    /**
1105     * Return the LoaderManager for this fragment, creating it if needed.
1106     */
1107    public LoaderManager getLoaderManager() {
1108        if (mLoaderManager != null) {
1109            return mLoaderManager;
1110        }
1111        if (mHost == null) {
1112            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1113        }
1114        mCheckedForLoaderManager = true;
1115        mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, true);
1116        return mLoaderManager;
1117    }
1118
1119    /**
1120     * Call {@link Activity#startActivity(Intent)} from the fragment's
1121     * containing Activity.
1122     *
1123     * @param intent The intent to start.
1124     */
1125    public void startActivity(Intent intent) {
1126        startActivity(intent, null);
1127    }
1128
1129    /**
1130     * Call {@link Activity#startActivity(Intent, Bundle)} from the fragment's
1131     * containing Activity.
1132     *
1133     * @param intent The intent to start.
1134     * @param options Additional options for how the Activity should be started.
1135     * See {@link android.content.Context#startActivity(Intent, Bundle)}
1136     * Context.startActivity(Intent, Bundle)} for more details.
1137     */
1138    public void startActivity(Intent intent, Bundle options) {
1139        if (mHost == null) {
1140            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1141        }
1142        if (options != null) {
1143            mHost.onStartActivityFromFragment(this, intent, -1, options);
1144        } else {
1145            // Note we want to go through this call for compatibility with
1146            // applications that may have overridden the method.
1147            mHost.onStartActivityFromFragment(this, intent, -1, null /*options*/);
1148        }
1149    }
1150
1151    /**
1152     * Call {@link Activity#startActivityForResult(Intent, int)} from the fragment's
1153     * containing Activity.
1154     */
1155    public void startActivityForResult(Intent intent, int requestCode) {
1156        startActivityForResult(intent, requestCode, null);
1157    }
1158
1159    /**
1160     * Call {@link Activity#startActivityForResult(Intent, int, Bundle)} from the fragment's
1161     * containing Activity.
1162     */
1163    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
1164        if (mHost == null) {
1165            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1166        }
1167        mHost.onStartActivityFromFragment(this, intent, requestCode, options);
1168    }
1169
1170    /**
1171     * Call {@link Activity#startIntentSenderForResult(IntentSender, int, Intent, int, int, int,
1172     * Bundle)} from the fragment's containing Activity.
1173     */
1174    public void startIntentSenderForResult(IntentSender intent, int requestCode,
1175            @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
1176            Bundle options) throws IntentSender.SendIntentException {
1177        if (mHost == null) {
1178            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1179        }
1180        mHost.onStartIntentSenderFromFragment(this, intent, requestCode, fillInIntent, flagsMask,
1181                flagsValues, extraFlags, options);
1182    }
1183
1184    /**
1185     * Receive the result from a previous call to
1186     * {@link #startActivityForResult(Intent, int)}.  This follows the
1187     * related Activity API as described there in
1188     * {@link Activity#onActivityResult(int, int, Intent)}.
1189     *
1190     * @param requestCode The integer request code originally supplied to
1191     *                    startActivityForResult(), allowing you to identify who this
1192     *                    result came from.
1193     * @param resultCode The integer result code returned by the child activity
1194     *                   through its setResult().
1195     * @param data An Intent, which can return result data to the caller
1196     *               (various data can be attached to Intent "extras").
1197     */
1198    public void onActivityResult(int requestCode, int resultCode, Intent data) {
1199    }
1200
1201    /**
1202     * Requests permissions to be granted to this application. These permissions
1203     * must be requested in your manifest, they should not be granted to your app,
1204     * and they should have protection level {@link android.content.pm.PermissionInfo
1205     * #PROTECTION_DANGEROUS dangerous}, regardless whether they are declared by
1206     * the platform or a third-party app.
1207     * <p>
1208     * Normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_NORMAL}
1209     * are granted at install time if requested in the manifest. Signature permissions
1210     * {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at
1211     * install time if requested in the manifest and the signature of your app matches
1212     * the signature of the app declaring the permissions.
1213     * </p>
1214     * <p>
1215     * If your app does not have the requested permissions the user will be presented
1216     * with UI for accepting them. After the user has accepted or rejected the
1217     * requested permissions you will receive a callback on {@link
1218     * #onRequestPermissionsResult(int, String[], int[])} reporting whether the
1219     * permissions were granted or not.
1220     * </p>
1221     * <p>
1222     * Note that requesting a permission does not guarantee it will be granted and
1223     * your app should be able to run without having this permission.
1224     * </p>
1225     * <p>
1226     * This method may start an activity allowing the user to choose which permissions
1227     * to grant and which to reject. Hence, you should be prepared that your activity
1228     * may be paused and resumed. Further, granting some permissions may require
1229     * a restart of you application. In such a case, the system will recreate the
1230     * activity stack before delivering the result to {@link
1231     * #onRequestPermissionsResult(int, String[], int[])}.
1232     * </p>
1233     * <p>
1234     * When checking whether you have a permission you should use {@link
1235     * android.content.Context#checkSelfPermission(String)}.
1236     * </p>
1237     * <p>
1238     * Calling this API for permissions already granted to your app would show UI
1239     * to the user to decide whether the app can still hold these permissions. This
1240     * can be useful if the way your app uses data guarded by the permissions
1241     * changes significantly.
1242     * </p>
1243     * <p>
1244     * You cannot request a permission if your activity sets {@link
1245     * android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
1246     * <code>true</code> because in this case the activity would not receive
1247     * result callbacks including {@link #onRequestPermissionsResult(int, String[], int[])}.
1248     * </p>
1249     * <p>
1250     * A sample permissions request looks like this:
1251     * </p>
1252     * <code><pre><p>
1253     * private void showContacts() {
1254     *     if (getActivity().checkSelfPermission(Manifest.permission.READ_CONTACTS)
1255     *             != PackageManager.PERMISSION_GRANTED) {
1256     *         requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},
1257     *                 PERMISSIONS_REQUEST_READ_CONTACTS);
1258     *     } else {
1259     *         doShowContacts();
1260     *     }
1261     * }
1262     *
1263     * {@literal @}Override
1264     * public void onRequestPermissionsResult(int requestCode, String[] permissions,
1265     *         int[] grantResults) {
1266     *     if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS
1267     *             && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
1268     *         doShowContacts();
1269     *     }
1270     * }
1271     * </code></pre></p>
1272     *
1273     * @param permissions The requested permissions. Must me non-null and not empty.
1274     * @param requestCode Application specific request code to match with a result
1275     *    reported to {@link #onRequestPermissionsResult(int, String[], int[])}.
1276     *    Should be >= 0.
1277     *
1278     * @see #onRequestPermissionsResult(int, String[], int[])
1279     * @see android.content.Context#checkSelfPermission(String)
1280     */
1281    public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
1282        if (mHost == null) {
1283            throw new IllegalStateException("Fragment " + this + " not attached to Activity");
1284        }
1285        mHost.onRequestPermissionsFromFragment(this, permissions,requestCode);
1286    }
1287
1288    /**
1289     * Callback for the result from requesting permissions. This method
1290     * is invoked for every call on {@link #requestPermissions(String[], int)}.
1291     * <p>
1292     * <strong>Note:</strong> It is possible that the permissions request interaction
1293     * with the user is interrupted. In this case you will receive empty permissions
1294     * and results arrays which should be treated as a cancellation.
1295     * </p>
1296     *
1297     * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
1298     * @param permissions The requested permissions. Never null.
1299     * @param grantResults The grant results for the corresponding permissions
1300     *     which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED}
1301     *     or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null.
1302     *
1303     * @see #requestPermissions(String[], int)
1304     */
1305    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
1306            @NonNull int[] grantResults) {
1307        /* callback - do nothing */
1308    }
1309
1310    /**
1311     * Gets whether you should show UI with rationale for requesting a permission.
1312     * You should do this only if you do not have the permission and the context in
1313     * which the permission is requested does not clearly communicate to the user
1314     * what would be the benefit from granting this permission.
1315     * <p>
1316     * For example, if you write a camera app, requesting the camera permission
1317     * would be expected by the user and no rationale for why it is requested is
1318     * needed. If however, the app needs location for tagging photos then a non-tech
1319     * savvy user may wonder how location is related to taking photos. In this case
1320     * you may choose to show UI with rationale of requesting this permission.
1321     * </p>
1322     *
1323     * @param permission A permission your app wants to request.
1324     * @return Whether you can show permission rationale UI.
1325     *
1326     * @see Context#checkSelfPermission(String)
1327     * @see #requestPermissions(String[], int)
1328     * @see #onRequestPermissionsResult(int, String[], int[])
1329     */
1330    public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
1331        if (mHost != null) {
1332            return mHost.getContext().getPackageManager()
1333                    .shouldShowRequestPermissionRationale(permission);
1334        }
1335        return false;
1336    }
1337
1338    /**
1339     * @hide Hack so that DialogFragment can make its Dialog before creating
1340     * its views, and the view construction can use the dialog's context for
1341     * inflation.  Maybe this should become a public API. Note sure.
1342     */
1343    public LayoutInflater getLayoutInflater(Bundle savedInstanceState) {
1344        final LayoutInflater result = mHost.onGetLayoutInflater();
1345        if (mHost.onUseFragmentManagerInflaterFactory()) {
1346            getChildFragmentManager(); // Init if needed; use raw implementation below.
1347            result.setPrivateFactory(mChildFragmentManager.getLayoutInflaterFactory());
1348        }
1349        return result;
1350    }
1351
1352    /**
1353     * @deprecated Use {@link #onInflate(Context, AttributeSet, Bundle)} instead.
1354     */
1355    @Deprecated
1356    @CallSuper
1357    public void onInflate(AttributeSet attrs, Bundle savedInstanceState) {
1358        mCalled = true;
1359    }
1360
1361    /**
1362     * Called when a fragment is being created as part of a view layout
1363     * inflation, typically from setting the content view of an activity.  This
1364     * may be called immediately after the fragment is created from a <fragment>
1365     * tag in a layout file.  Note this is <em>before</em> the fragment's
1366     * {@link #onAttach(Activity)} has been called; all you should do here is
1367     * parse the attributes and save them away.
1368     *
1369     * <p>This is called every time the fragment is inflated, even if it is
1370     * being inflated into a new instance with saved state.  It typically makes
1371     * sense to re-parse the parameters each time, to allow them to change with
1372     * different configurations.</p>
1373     *
1374     * <p>Here is a typical implementation of a fragment that can take parameters
1375     * both through attributes supplied here as well from {@link #getArguments()}:</p>
1376     *
1377     * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
1378     *      fragment}
1379     *
1380     * <p>Note that parsing the XML attributes uses a "styleable" resource.  The
1381     * declaration for the styleable used here is:</p>
1382     *
1383     * {@sample development/samples/ApiDemos/res/values/attrs.xml fragment_arguments}
1384     *
1385     * <p>The fragment can then be declared within its activity's content layout
1386     * through a tag like this:</p>
1387     *
1388     * {@sample development/samples/ApiDemos/res/layout/fragment_arguments.xml from_attributes}
1389     *
1390     * <p>This fragment can also be created dynamically from arguments given
1391     * at runtime in the arguments Bundle; here is an example of doing so at
1392     * creation of the containing activity:</p>
1393     *
1394     * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
1395     *      create}
1396     *
1397     * @param context The Context that is inflating this fragment.
1398     * @param attrs The attributes at the tag where the fragment is
1399     * being created.
1400     * @param savedInstanceState If the fragment is being re-created from
1401     * a previous saved state, this is the state.
1402     */
1403    @CallSuper
1404    public void onInflate(Context context, AttributeSet attrs, Bundle savedInstanceState) {
1405        onInflate(attrs, savedInstanceState);
1406        mCalled = true;
1407
1408        TypedArray a = context.obtainStyledAttributes(attrs,
1409                com.android.internal.R.styleable.Fragment);
1410        setEnterTransition(loadTransition(context, a, getEnterTransition(), null,
1411                com.android.internal.R.styleable.Fragment_fragmentEnterTransition));
1412        setReturnTransition(loadTransition(context, a, getReturnTransition(),
1413                USE_DEFAULT_TRANSITION,
1414                com.android.internal.R.styleable.Fragment_fragmentReturnTransition));
1415        setExitTransition(loadTransition(context, a, getExitTransition(), null,
1416                com.android.internal.R.styleable.Fragment_fragmentExitTransition));
1417
1418        setReenterTransition(loadTransition(context, a, getReenterTransition(),
1419                USE_DEFAULT_TRANSITION,
1420                com.android.internal.R.styleable.Fragment_fragmentReenterTransition));
1421        setSharedElementEnterTransition(loadTransition(context, a,
1422                getSharedElementEnterTransition(), null,
1423                com.android.internal.R.styleable.Fragment_fragmentSharedElementEnterTransition));
1424        setSharedElementReturnTransition(loadTransition(context, a,
1425                getSharedElementReturnTransition(), USE_DEFAULT_TRANSITION,
1426                com.android.internal.R.styleable.Fragment_fragmentSharedElementReturnTransition));
1427        boolean isEnterSet;
1428        boolean isReturnSet;
1429        if (mAnimationInfo == null) {
1430            isEnterSet = false;
1431            isReturnSet = false;
1432        } else {
1433            isEnterSet = mAnimationInfo.mAllowEnterTransitionOverlap != null;
1434            isReturnSet = mAnimationInfo.mAllowReturnTransitionOverlap != null;
1435        }
1436        if (!isEnterSet) {
1437            setAllowEnterTransitionOverlap(a.getBoolean(
1438                    com.android.internal.R.styleable.Fragment_fragmentAllowEnterTransitionOverlap,
1439                    true));
1440        }
1441        if (!isReturnSet) {
1442            setAllowReturnTransitionOverlap(a.getBoolean(
1443                    com.android.internal.R.styleable.Fragment_fragmentAllowReturnTransitionOverlap,
1444                    true));
1445        }
1446        a.recycle();
1447
1448        final Activity hostActivity = mHost == null ? null : mHost.getActivity();
1449        if (hostActivity != null) {
1450            mCalled = false;
1451            onInflate(hostActivity, attrs, savedInstanceState);
1452        }
1453    }
1454
1455    /**
1456     * @deprecated Use {@link #onInflate(Context, AttributeSet, Bundle)} instead.
1457     */
1458    @Deprecated
1459    @CallSuper
1460    public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
1461        mCalled = true;
1462    }
1463
1464    /**
1465     * Called when a fragment is attached as a child of this fragment.
1466     *
1467     * <p>This is called after the attached fragment's <code>onAttach</code> and before
1468     * the attached fragment's <code>onCreate</code> if the fragment has not yet had a previous
1469     * call to <code>onCreate</code>.</p>
1470     *
1471     * @param childFragment child fragment being attached
1472     */
1473    public void onAttachFragment(Fragment childFragment) {
1474    }
1475
1476    /**
1477     * Called when a fragment is first attached to its context.
1478     * {@link #onCreate(Bundle)} will be called after this.
1479     */
1480    @CallSuper
1481    public void onAttach(Context context) {
1482        mCalled = true;
1483        final Activity hostActivity = mHost == null ? null : mHost.getActivity();
1484        if (hostActivity != null) {
1485            mCalled = false;
1486            onAttach(hostActivity);
1487        }
1488    }
1489
1490    /**
1491     * @deprecated Use {@link #onAttach(Context)} instead.
1492     */
1493    @Deprecated
1494    @CallSuper
1495    public void onAttach(Activity activity) {
1496        mCalled = true;
1497    }
1498
1499    /**
1500     * Called when a fragment loads an animation.
1501     */
1502    public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) {
1503        return null;
1504    }
1505
1506    /**
1507     * Called to do initial creation of a fragment.  This is called after
1508     * {@link #onAttach(Activity)} and before
1509     * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}, but is not called if the fragment
1510     * instance is retained across Activity re-creation (see {@link #setRetainInstance(boolean)}).
1511     *
1512     * <p>Note that this can be called while the fragment's activity is
1513     * still in the process of being created.  As such, you can not rely
1514     * on things like the activity's content view hierarchy being initialized
1515     * at this point.  If you want to do work once the activity itself is
1516     * created, see {@link #onActivityCreated(Bundle)}.
1517     *
1518     * <p>If your app's <code>targetSdkVersion</code> is {@link android.os.Build.VERSION_CODES#M}
1519     * or lower, child fragments being restored from the savedInstanceState are restored after
1520     * <code>onCreate</code> returns. When targeting {@link android.os.Build.VERSION_CODES#N} or
1521     * above and running on an N or newer platform version
1522     * they are restored by <code>Fragment.onCreate</code>.</p>
1523     *
1524     * @param savedInstanceState If the fragment is being re-created from
1525     * a previous saved state, this is the state.
1526     */
1527    @CallSuper
1528    public void onCreate(@Nullable Bundle savedInstanceState) {
1529        mCalled = true;
1530        final Context context = getContext();
1531        final int version = context != null ? context.getApplicationInfo().targetSdkVersion : 0;
1532        if (version >= Build.VERSION_CODES.N) {
1533            restoreChildFragmentState(savedInstanceState, true);
1534            if (mChildFragmentManager != null
1535                    && !mChildFragmentManager.isStateAtLeast(Fragment.CREATED)) {
1536                mChildFragmentManager.dispatchCreate();
1537            }
1538        }
1539    }
1540
1541    void restoreChildFragmentState(@Nullable Bundle savedInstanceState, boolean provideNonConfig) {
1542        if (savedInstanceState != null) {
1543            Parcelable p = savedInstanceState.getParcelable(Activity.FRAGMENTS_TAG);
1544            if (p != null) {
1545                if (mChildFragmentManager == null) {
1546                    instantiateChildFragmentManager();
1547                }
1548                mChildFragmentManager.restoreAllState(p, provideNonConfig ? mChildNonConfig : null);
1549                mChildNonConfig = null;
1550                mChildFragmentManager.dispatchCreate();
1551            }
1552        }
1553    }
1554
1555    /**
1556     * Called to have the fragment instantiate its user interface view.
1557     * This is optional, and non-graphical fragments can return null (which
1558     * is the default implementation).  This will be called between
1559     * {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}.
1560     *
1561     * <p>If you return a View from here, you will later be called in
1562     * {@link #onDestroyView} when the view is being released.
1563     *
1564     * @param inflater The LayoutInflater object that can be used to inflate
1565     * any views in the fragment,
1566     * @param container If non-null, this is the parent view that the fragment's
1567     * UI should be attached to.  The fragment should not add the view itself,
1568     * but this can be used to generate the LayoutParams of the view.
1569     * @param savedInstanceState If non-null, this fragment is being re-constructed
1570     * from a previous saved state as given here.
1571     *
1572     * @return Return the View for the fragment's UI, or null.
1573     */
1574    @Nullable
1575    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
1576            Bundle savedInstanceState) {
1577        return null;
1578    }
1579
1580    /**
1581     * Called immediately after {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}
1582     * has returned, but before any saved state has been restored in to the view.
1583     * This gives subclasses a chance to initialize themselves once
1584     * they know their view hierarchy has been completely created.  The fragment's
1585     * view hierarchy is not however attached to its parent at this point.
1586     * @param view The View returned by {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
1587     * @param savedInstanceState If non-null, this fragment is being re-constructed
1588     * from a previous saved state as given here.
1589     */
1590    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
1591    }
1592
1593    /**
1594     * Get the root view for the fragment's layout (the one returned by {@link #onCreateView}),
1595     * if provided.
1596     *
1597     * @return The fragment's root view, or null if it has no layout.
1598     */
1599    @Nullable
1600    public View getView() {
1601        return mView;
1602    }
1603
1604    /**
1605     * Called when the fragment's activity has been created and this
1606     * fragment's view hierarchy instantiated.  It can be used to do final
1607     * initialization once these pieces are in place, such as retrieving
1608     * views or restoring state.  It is also useful for fragments that use
1609     * {@link #setRetainInstance(boolean)} to retain their instance,
1610     * as this callback tells the fragment when it is fully associated with
1611     * the new activity instance.  This is called after {@link #onCreateView}
1612     * and before {@link #onViewStateRestored(Bundle)}.
1613     *
1614     * @param savedInstanceState If the fragment is being re-created from
1615     * a previous saved state, this is the state.
1616     */
1617    @CallSuper
1618    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
1619        mCalled = true;
1620    }
1621
1622    /**
1623     * Called when all saved state has been restored into the view hierarchy
1624     * of the fragment.  This can be used to do initialization based on saved
1625     * state that you are letting the view hierarchy track itself, such as
1626     * whether check box widgets are currently checked.  This is called
1627     * after {@link #onActivityCreated(Bundle)} and before
1628     * {@link #onStart()}.
1629     *
1630     * @param savedInstanceState If the fragment is being re-created from
1631     * a previous saved state, this is the state.
1632     */
1633    @CallSuper
1634    public void onViewStateRestored(Bundle savedInstanceState) {
1635        mCalled = true;
1636    }
1637
1638    /**
1639     * Called when the Fragment is visible to the user.  This is generally
1640     * tied to {@link Activity#onStart() Activity.onStart} of the containing
1641     * Activity's lifecycle.
1642     */
1643    @CallSuper
1644    public void onStart() {
1645        mCalled = true;
1646
1647        if (!mLoadersStarted) {
1648            mLoadersStarted = true;
1649            if (!mCheckedForLoaderManager) {
1650                mCheckedForLoaderManager = true;
1651                mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, false);
1652            }
1653            if (mLoaderManager != null) {
1654                mLoaderManager.doStart();
1655            }
1656        }
1657    }
1658
1659    /**
1660     * Called when the fragment is visible to the user and actively running.
1661     * This is generally
1662     * tied to {@link Activity#onResume() Activity.onResume} of the containing
1663     * Activity's lifecycle.
1664     */
1665    @CallSuper
1666    public void onResume() {
1667        mCalled = true;
1668    }
1669
1670    /**
1671     * Called to ask the fragment to save its current dynamic state, so it
1672     * can later be reconstructed in a new instance of its process is
1673     * restarted.  If a new instance of the fragment later needs to be
1674     * created, the data you place in the Bundle here will be available
1675     * in the Bundle given to {@link #onCreate(Bundle)},
1676     * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}, and
1677     * {@link #onActivityCreated(Bundle)}.
1678     *
1679     * <p>This corresponds to {@link Activity#onSaveInstanceState(Bundle)
1680     * Activity.onSaveInstanceState(Bundle)} and most of the discussion there
1681     * applies here as well.  Note however: <em>this method may be called
1682     * at any time before {@link #onDestroy()}</em>.  There are many situations
1683     * where a fragment may be mostly torn down (such as when placed on the
1684     * back stack with no UI showing), but its state will not be saved until
1685     * its owning activity actually needs to save its state.
1686     *
1687     * @param outState Bundle in which to place your saved state.
1688     */
1689    public void onSaveInstanceState(Bundle outState) {
1690    }
1691
1692    /**
1693     * Called when the Fragment's activity changes from fullscreen mode to multi-window mode and
1694     * visa-versa. This is generally tied to {@link Activity#onMultiWindowModeChanged} of the
1695     * containing Activity.
1696     *
1697     * @param isInMultiWindowMode True if the activity is in multi-window mode.
1698     */
1699    public void onMultiWindowModeChanged(boolean isInMultiWindowMode) {
1700    }
1701
1702    /**
1703     * Called by the system when the activity changes to and from picture-in-picture mode. This is
1704     * generally tied to {@link Activity#onPictureInPictureModeChanged} of the containing Activity.
1705     *
1706     * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode.
1707     */
1708    public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
1709    }
1710
1711    @CallSuper
1712    public void onConfigurationChanged(Configuration newConfig) {
1713        mCalled = true;
1714    }
1715
1716    /**
1717     * Called when the Fragment is no longer resumed.  This is generally
1718     * tied to {@link Activity#onPause() Activity.onPause} of the containing
1719     * Activity's lifecycle.
1720     */
1721    @CallSuper
1722    public void onPause() {
1723        mCalled = true;
1724    }
1725
1726    /**
1727     * Called when the Fragment is no longer started.  This is generally
1728     * tied to {@link Activity#onStop() Activity.onStop} of the containing
1729     * Activity's lifecycle.
1730     */
1731    @CallSuper
1732    public void onStop() {
1733        mCalled = true;
1734    }
1735
1736    @CallSuper
1737    public void onLowMemory() {
1738        mCalled = true;
1739    }
1740
1741    @CallSuper
1742    public void onTrimMemory(int level) {
1743        mCalled = true;
1744    }
1745
1746    /**
1747     * Called when the view previously created by {@link #onCreateView} has
1748     * been detached from the fragment.  The next time the fragment needs
1749     * to be displayed, a new view will be created.  This is called
1750     * after {@link #onStop()} and before {@link #onDestroy()}.  It is called
1751     * <em>regardless</em> of whether {@link #onCreateView} returned a
1752     * non-null view.  Internally it is called after the view's state has
1753     * been saved but before it has been removed from its parent.
1754     */
1755    @CallSuper
1756    public void onDestroyView() {
1757        mCalled = true;
1758    }
1759
1760    /**
1761     * Called when the fragment is no longer in use.  This is called
1762     * after {@link #onStop()} and before {@link #onDetach()}.
1763     */
1764    @CallSuper
1765    public void onDestroy() {
1766        mCalled = true;
1767        //Log.v("foo", "onDestroy: mCheckedForLoaderManager=" + mCheckedForLoaderManager
1768        //        + " mLoaderManager=" + mLoaderManager);
1769        if (!mCheckedForLoaderManager) {
1770            mCheckedForLoaderManager = true;
1771            mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, false);
1772        }
1773        if (mLoaderManager != null) {
1774            mLoaderManager.doDestroy();
1775        }
1776    }
1777
1778    /**
1779     * Called by the fragment manager once this fragment has been removed,
1780     * so that we don't have any left-over state if the application decides
1781     * to re-use the instance.  This only clears state that the framework
1782     * internally manages, not things the application sets.
1783     */
1784    void initState() {
1785        mIndex = -1;
1786        mWho = null;
1787        mAdded = false;
1788        mRemoving = false;
1789        mFromLayout = false;
1790        mInLayout = false;
1791        mRestored = false;
1792        mBackStackNesting = 0;
1793        mFragmentManager = null;
1794        mChildFragmentManager = null;
1795        mHost = null;
1796        mFragmentId = 0;
1797        mContainerId = 0;
1798        mTag = null;
1799        mHidden = false;
1800        mDetached = false;
1801        mRetaining = false;
1802        mLoaderManager = null;
1803        mLoadersStarted = false;
1804        mCheckedForLoaderManager = false;
1805    }
1806
1807    /**
1808     * Called when the fragment is no longer attached to its activity.  This is called after
1809     * {@link #onDestroy()}, except in the cases where the fragment instance is retained across
1810     * Activity re-creation (see {@link #setRetainInstance(boolean)}), in which case it is called
1811     * after {@link #onStop()}.
1812     */
1813    @CallSuper
1814    public void onDetach() {
1815        mCalled = true;
1816    }
1817
1818    /**
1819     * Initialize the contents of the Activity's standard options menu.  You
1820     * should place your menu items in to <var>menu</var>.  For this method
1821     * to be called, you must have first called {@link #setHasOptionsMenu}.  See
1822     * {@link Activity#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu}
1823     * for more information.
1824     *
1825     * @param menu The options menu in which you place your items.
1826     *
1827     * @see #setHasOptionsMenu
1828     * @see #onPrepareOptionsMenu
1829     * @see #onOptionsItemSelected
1830     */
1831    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
1832    }
1833
1834    /**
1835     * Prepare the Screen's standard options menu to be displayed.  This is
1836     * called right before the menu is shown, every time it is shown.  You can
1837     * use this method to efficiently enable/disable items or otherwise
1838     * dynamically modify the contents.  See
1839     * {@link Activity#onPrepareOptionsMenu(Menu) Activity.onPrepareOptionsMenu}
1840     * for more information.
1841     *
1842     * @param menu The options menu as last shown or first initialized by
1843     *             onCreateOptionsMenu().
1844     *
1845     * @see #setHasOptionsMenu
1846     * @see #onCreateOptionsMenu
1847     */
1848    public void onPrepareOptionsMenu(Menu menu) {
1849    }
1850
1851    /**
1852     * Called when this fragment's option menu items are no longer being
1853     * included in the overall options menu.  Receiving this call means that
1854     * the menu needed to be rebuilt, but this fragment's items were not
1855     * included in the newly built menu (its {@link #onCreateOptionsMenu(Menu, MenuInflater)}
1856     * was not called).
1857     */
1858    public void onDestroyOptionsMenu() {
1859    }
1860
1861    /**
1862     * This hook is called whenever an item in your options menu is selected.
1863     * The default implementation simply returns false to have the normal
1864     * processing happen (calling the item's Runnable or sending a message to
1865     * its Handler as appropriate).  You can use this method for any items
1866     * for which you would like to do processing without those other
1867     * facilities.
1868     *
1869     * <p>Derived classes should call through to the base class for it to
1870     * perform the default menu handling.
1871     *
1872     * @param item The menu item that was selected.
1873     *
1874     * @return boolean Return false to allow normal menu processing to
1875     *         proceed, true to consume it here.
1876     *
1877     * @see #onCreateOptionsMenu
1878     */
1879    public boolean onOptionsItemSelected(MenuItem item) {
1880        return false;
1881    }
1882
1883    /**
1884     * This hook is called whenever the options menu is being closed (either by the user canceling
1885     * the menu with the back/menu button, or when an item is selected).
1886     *
1887     * @param menu The options menu as last shown or first initialized by
1888     *             onCreateOptionsMenu().
1889     */
1890    public void onOptionsMenuClosed(Menu menu) {
1891    }
1892
1893    /**
1894     * Called when a context menu for the {@code view} is about to be shown.
1895     * Unlike {@link #onCreateOptionsMenu}, this will be called every
1896     * time the context menu is about to be shown and should be populated for
1897     * the view (or item inside the view for {@link AdapterView} subclasses,
1898     * this can be found in the {@code menuInfo})).
1899     * <p>
1900     * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
1901     * item has been selected.
1902     * <p>
1903     * The default implementation calls up to
1904     * {@link Activity#onCreateContextMenu Activity.onCreateContextMenu}, though
1905     * you can not call this implementation if you don't want that behavior.
1906     * <p>
1907     * It is not safe to hold onto the context menu after this method returns.
1908     * {@inheritDoc}
1909     */
1910    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1911        getActivity().onCreateContextMenu(menu, v, menuInfo);
1912    }
1913
1914    /**
1915     * Registers a context menu to be shown for the given view (multiple views
1916     * can show the context menu). This method will set the
1917     * {@link OnCreateContextMenuListener} on the view to this fragment, so
1918     * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
1919     * called when it is time to show the context menu.
1920     *
1921     * @see #unregisterForContextMenu(View)
1922     * @param view The view that should show a context menu.
1923     */
1924    public void registerForContextMenu(View view) {
1925        view.setOnCreateContextMenuListener(this);
1926    }
1927
1928    /**
1929     * Prevents a context menu to be shown for the given view. This method will
1930     * remove the {@link OnCreateContextMenuListener} on the view.
1931     *
1932     * @see #registerForContextMenu(View)
1933     * @param view The view that should stop showing a context menu.
1934     */
1935    public void unregisterForContextMenu(View view) {
1936        view.setOnCreateContextMenuListener(null);
1937    }
1938
1939    /**
1940     * This hook is called whenever an item in a context menu is selected. The
1941     * default implementation simply returns false to have the normal processing
1942     * happen (calling the item's Runnable or sending a message to its Handler
1943     * as appropriate). You can use this method for any items for which you
1944     * would like to do processing without those other facilities.
1945     * <p>
1946     * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
1947     * View that added this menu item.
1948     * <p>
1949     * Derived classes should call through to the base class for it to perform
1950     * the default menu handling.
1951     *
1952     * @param item The context menu item that was selected.
1953     * @return boolean Return false to allow normal context menu processing to
1954     *         proceed, true to consume it here.
1955     */
1956    public boolean onContextItemSelected(MenuItem item) {
1957        return false;
1958    }
1959
1960    /**
1961     * When custom transitions are used with Fragments, the enter transition callback
1962     * is called when this Fragment is attached or detached when not popping the back stack.
1963     *
1964     * @param callback Used to manipulate the shared element transitions on this Fragment
1965     *                 when added not as a pop from the back stack.
1966     */
1967    public void setEnterSharedElementCallback(SharedElementCallback callback) {
1968        if (callback == null) {
1969            if (mAnimationInfo == null) {
1970                return; // already a null callback
1971            }
1972            callback = SharedElementCallback.NULL_CALLBACK;
1973        }
1974        ensureAnimationInfo().mEnterTransitionCallback = callback;
1975    }
1976
1977    /**
1978     * When custom transitions are used with Fragments, the exit transition callback
1979     * is called when this Fragment is attached or detached when popping the back stack.
1980     *
1981     * @param callback Used to manipulate the shared element transitions on this Fragment
1982     *                 when added as a pop from the back stack.
1983     */
1984    public void setExitSharedElementCallback(SharedElementCallback callback) {
1985        if (callback == null) {
1986            if (mAnimationInfo == null) {
1987                return; // already a null callback
1988            }
1989            callback = SharedElementCallback.NULL_CALLBACK;
1990        }
1991        ensureAnimationInfo().mExitTransitionCallback = callback;
1992    }
1993
1994    /**
1995     * Sets the Transition that will be used to move Views into the initial scene. The entering
1996     * Views will be those that are regular Views or ViewGroups that have
1997     * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
1998     * {@link android.transition.Visibility} as entering is governed by changing visibility from
1999     * {@link View#INVISIBLE} to {@link View#VISIBLE}. If <code>transition</code> is null,
2000     * entering Views will remain unaffected.
2001     *
2002     * @param transition The Transition to use to move Views into the initial Scene.
2003     * @attr ref android.R.styleable#Fragment_fragmentEnterTransition
2004     */
2005    public void setEnterTransition(Transition transition) {
2006        if (shouldChangeTransition(transition, null)) {
2007            ensureAnimationInfo().mEnterTransition = transition;
2008        }
2009    }
2010
2011    /**
2012     * Returns the Transition that will be used to move Views into the initial scene. The entering
2013     * Views will be those that are regular Views or ViewGroups that have
2014     * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
2015     * {@link android.transition.Visibility} as entering is governed by changing visibility from
2016     * {@link View#INVISIBLE} to {@link View#VISIBLE}.
2017     *
2018     * @return the Transition to use to move Views into the initial Scene.
2019     * @attr ref android.R.styleable#Fragment_fragmentEnterTransition
2020     */
2021    public Transition getEnterTransition() {
2022        if (mAnimationInfo == null) {
2023            return null;
2024        }
2025        return mAnimationInfo.mEnterTransition;
2026    }
2027
2028    /**
2029     * Sets the Transition that will be used to move Views out of the scene when the Fragment is
2030     * preparing to be removed, hidden, or detached because of popping the back stack. The exiting
2031     * Views will be those that are regular Views or ViewGroups that have
2032     * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
2033     * {@link android.transition.Visibility} as entering is governed by changing visibility from
2034     * {@link View#VISIBLE} to {@link View#INVISIBLE}. If <code>transition</code> is null,
2035     * entering Views will remain unaffected. If nothing is set, the default will be to
2036     * use the same value as set in {@link #setEnterTransition(android.transition.Transition)}.
2037     *
2038     * @param transition The Transition to use to move Views out of the Scene when the Fragment
2039     *                   is preparing to close.
2040     * @attr ref android.R.styleable#Fragment_fragmentExitTransition
2041     */
2042    public void setReturnTransition(Transition transition) {
2043        if (shouldChangeTransition(transition, USE_DEFAULT_TRANSITION)) {
2044            ensureAnimationInfo().mReturnTransition = transition;
2045        }
2046    }
2047
2048    /**
2049     * Returns the Transition that will be used to move Views out of the scene when the Fragment is
2050     * preparing to be removed, hidden, or detached because of popping the back stack. The exiting
2051     * Views will be those that are regular Views or ViewGroups that have
2052     * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
2053     * {@link android.transition.Visibility} as entering is governed by changing visibility from
2054     * {@link View#VISIBLE} to {@link View#INVISIBLE}. If <code>transition</code> is null,
2055     * entering Views will remain unaffected.
2056     *
2057     * @return the Transition to use to move Views out of the Scene when the Fragment
2058     *         is preparing to close.
2059     * @attr ref android.R.styleable#Fragment_fragmentExitTransition
2060     */
2061    public Transition getReturnTransition() {
2062        if (mAnimationInfo == null) {
2063            return null;
2064        }
2065        return mAnimationInfo.mReturnTransition == USE_DEFAULT_TRANSITION ? getEnterTransition()
2066                : mAnimationInfo.mReturnTransition;
2067    }
2068
2069    /**
2070     * Sets the Transition that will be used to move Views out of the scene when the
2071     * fragment is removed, hidden, or detached when not popping the back stack.
2072     * The exiting Views will be those that are regular Views or ViewGroups that
2073     * have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
2074     * {@link android.transition.Visibility} as exiting is governed by changing visibility
2075     * from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null, the views will
2076     * remain unaffected.
2077     *
2078     * @param transition The Transition to use to move Views out of the Scene when the Fragment
2079     *                   is being closed not due to popping the back stack.
2080     * @attr ref android.R.styleable#Fragment_fragmentExitTransition
2081     */
2082    public void setExitTransition(Transition transition) {
2083        if (shouldChangeTransition(transition, null)) {
2084            ensureAnimationInfo().mExitTransition = transition;
2085        }
2086    }
2087
2088    /**
2089     * Returns the Transition that will be used to move Views out of the scene when the
2090     * fragment is removed, hidden, or detached when not popping the back stack.
2091     * The exiting Views will be those that are regular Views or ViewGroups that
2092     * have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend
2093     * {@link android.transition.Visibility} as exiting is governed by changing visibility
2094     * from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null, the views will
2095     * remain unaffected.
2096     *
2097     * @return the Transition to use to move Views out of the Scene when the Fragment
2098     *         is being closed not due to popping the back stack.
2099     * @attr ref android.R.styleable#Fragment_fragmentExitTransition
2100     */
2101    public Transition getExitTransition() {
2102        if (mAnimationInfo == null) {
2103            return null;
2104        }
2105        return mAnimationInfo.mExitTransition;
2106    }
2107
2108    /**
2109     * Sets the Transition that will be used to move Views in to the scene when returning due
2110     * to popping a back stack. The entering Views will be those that are regular Views
2111     * or ViewGroups that have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions
2112     * will extend {@link android.transition.Visibility} as exiting is governed by changing
2113     * visibility from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null,
2114     * the views will remain unaffected. If nothing is set, the default will be to use the same
2115     * transition as {@link #setExitTransition(android.transition.Transition)}.
2116     *
2117     * @param transition The Transition to use to move Views into the scene when reentering from a
2118     *                   previously-started Activity.
2119     * @attr ref android.R.styleable#Fragment_fragmentReenterTransition
2120     */
2121    public void setReenterTransition(Transition transition) {
2122        if (shouldChangeTransition(transition, USE_DEFAULT_TRANSITION)) {
2123            ensureAnimationInfo().mReenterTransition = transition;
2124        }
2125    }
2126
2127    /**
2128     * Returns the Transition that will be used to move Views in to the scene when returning due
2129     * to popping a back stack. The entering Views will be those that are regular Views
2130     * or ViewGroups that have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions
2131     * will extend {@link android.transition.Visibility} as exiting is governed by changing
2132     * visibility from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null,
2133     * the views will remain unaffected. If nothing is set, the default will be to use the same
2134     * transition as {@link #setExitTransition(android.transition.Transition)}.
2135     *
2136     * @return the Transition to use to move Views into the scene when reentering from a
2137     *                   previously-started Activity.
2138     * @attr ref android.R.styleable#Fragment_fragmentReenterTransition
2139     */
2140    public Transition getReenterTransition() {
2141        if (mAnimationInfo == null) {
2142            return null;
2143        }
2144        return mAnimationInfo.mReenterTransition == USE_DEFAULT_TRANSITION ? getExitTransition()
2145                : mAnimationInfo.mReenterTransition;
2146    }
2147
2148    /**
2149     * Sets the Transition that will be used for shared elements transferred into the content
2150     * Scene. Typical Transitions will affect size and location, such as
2151     * {@link android.transition.ChangeBounds}. A null
2152     * value will cause transferred shared elements to blink to the final position.
2153     *
2154     * @param transition The Transition to use for shared elements transferred into the content
2155     *                   Scene.
2156     * @attr ref android.R.styleable#Fragment_fragmentSharedElementEnterTransition
2157     */
2158    public void setSharedElementEnterTransition(Transition transition) {
2159        if (shouldChangeTransition(transition, null)) {
2160            ensureAnimationInfo().mSharedElementEnterTransition = transition;
2161        }
2162    }
2163
2164    /**
2165     * Returns the Transition that will be used for shared elements transferred into the content
2166     * Scene. Typical Transitions will affect size and location, such as
2167     * {@link android.transition.ChangeBounds}. A null
2168     * value will cause transferred shared elements to blink to the final position.
2169     *
2170     * @return The Transition to use for shared elements transferred into the content
2171     *                   Scene.
2172     * @attr ref android.R.styleable#Fragment_fragmentSharedElementEnterTransition
2173     */
2174    public Transition getSharedElementEnterTransition() {
2175        if (mAnimationInfo == null) {
2176            return null;
2177        }
2178        return mAnimationInfo.mSharedElementEnterTransition;
2179    }
2180
2181    /**
2182     * Sets the Transition that will be used for shared elements transferred back during a
2183     * pop of the back stack. This Transition acts in the leaving Fragment.
2184     * Typical Transitions will affect size and location, such as
2185     * {@link android.transition.ChangeBounds}. A null
2186     * value will cause transferred shared elements to blink to the final position.
2187     * If no value is set, the default will be to use the same value as
2188     * {@link #setSharedElementEnterTransition(android.transition.Transition)}.
2189     *
2190     * @param transition The Transition to use for shared elements transferred out of the content
2191     *                   Scene.
2192     * @attr ref android.R.styleable#Fragment_fragmentSharedElementReturnTransition
2193     */
2194    public void setSharedElementReturnTransition(Transition transition) {
2195        if (shouldChangeTransition(transition, USE_DEFAULT_TRANSITION)) {
2196            ensureAnimationInfo().mSharedElementReturnTransition = transition;
2197        }
2198    }
2199
2200    /**
2201     * Return the Transition that will be used for shared elements transferred back during a
2202     * pop of the back stack. This Transition acts in the leaving Fragment.
2203     * Typical Transitions will affect size and location, such as
2204     * {@link android.transition.ChangeBounds}. A null
2205     * value will cause transferred shared elements to blink to the final position.
2206     * If no value is set, the default will be to use the same value as
2207     * {@link #setSharedElementEnterTransition(android.transition.Transition)}.
2208     *
2209     * @return The Transition to use for shared elements transferred out of the content
2210     *                   Scene.
2211     * @attr ref android.R.styleable#Fragment_fragmentSharedElementReturnTransition
2212     */
2213    public Transition getSharedElementReturnTransition() {
2214        if (mAnimationInfo == null) {
2215            return null;
2216        }
2217        return mAnimationInfo.mSharedElementReturnTransition == USE_DEFAULT_TRANSITION
2218                ? getSharedElementEnterTransition()
2219                : mAnimationInfo.mSharedElementReturnTransition;
2220    }
2221
2222    /**
2223     * Sets whether the the exit transition and enter transition overlap or not.
2224     * When true, the enter transition will start as soon as possible. When false, the
2225     * enter transition will wait until the exit transition completes before starting.
2226     *
2227     * @param allow true to start the enter transition when possible or false to
2228     *              wait until the exiting transition completes.
2229     * @attr ref android.R.styleable#Fragment_fragmentAllowEnterTransitionOverlap
2230     */
2231    public void setAllowEnterTransitionOverlap(boolean allow) {
2232        ensureAnimationInfo().mAllowEnterTransitionOverlap = allow;
2233    }
2234
2235    /**
2236     * Returns whether the the exit transition and enter transition overlap or not.
2237     * When true, the enter transition will start as soon as possible. When false, the
2238     * enter transition will wait until the exit transition completes before starting.
2239     *
2240     * @return true when the enter transition should start as soon as possible or false to
2241     * when it should wait until the exiting transition completes.
2242     * @attr ref android.R.styleable#Fragment_fragmentAllowEnterTransitionOverlap
2243     */
2244    public boolean getAllowEnterTransitionOverlap() {
2245        return (mAnimationInfo == null || mAnimationInfo.mAllowEnterTransitionOverlap == null)
2246                ? true : mAnimationInfo.mAllowEnterTransitionOverlap;
2247    }
2248
2249    /**
2250     * Sets whether the the return transition and reenter transition overlap or not.
2251     * When true, the reenter transition will start as soon as possible. When false, the
2252     * reenter transition will wait until the return transition completes before starting.
2253     *
2254     * @param allow true to start the reenter transition when possible or false to wait until the
2255     *              return transition completes.
2256     * @attr ref android.R.styleable#Fragment_fragmentAllowReturnTransitionOverlap
2257     */
2258    public void setAllowReturnTransitionOverlap(boolean allow) {
2259        ensureAnimationInfo().mAllowReturnTransitionOverlap = allow;
2260    }
2261
2262    /**
2263     * Returns whether the the return transition and reenter transition overlap or not.
2264     * When true, the reenter transition will start as soon as possible. When false, the
2265     * reenter transition will wait until the return transition completes before starting.
2266     *
2267     * @return true to start the reenter transition when possible or false to wait until the
2268     *         return transition completes.
2269     * @attr ref android.R.styleable#Fragment_fragmentAllowReturnTransitionOverlap
2270     */
2271    public boolean getAllowReturnTransitionOverlap() {
2272        return (mAnimationInfo == null || mAnimationInfo.mAllowReturnTransitionOverlap == null)
2273                ? true : mAnimationInfo.mAllowReturnTransitionOverlap;
2274    }
2275
2276    /**
2277     * Postpone the entering Fragment transition until {@link #startPostponedEnterTransition()}
2278     * or {@link FragmentManager#executePendingTransactions()} has been called.
2279     * <p>
2280     * This method gives the Fragment the ability to delay Fragment animations
2281     * until all data is loaded. Until then, the added, shown, and
2282     * attached Fragments will be INVISIBLE and removed, hidden, and detached Fragments won't
2283     * be have their Views removed. The transaction runs when all postponed added Fragments in the
2284     * transaction have called {@link #startPostponedEnterTransition()}.
2285     * <p>
2286     * This method should be called before being added to the FragmentTransaction or
2287     * in {@link #onCreate(Bundle), {@link #onAttach(Context)}, or
2288     * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}}.
2289     * {@link #startPostponedEnterTransition()} must be called to allow the Fragment to
2290     * start the transitions.
2291     * <p>
2292     * When a FragmentTransaction is started that may affect a postponed FragmentTransaction,
2293     * based on which containers are in their operations, the postponed FragmentTransaction
2294     * will have its start triggered. The early triggering may result in faulty or nonexistent
2295     * animations in the postponed transaction. FragmentTransactions that operate only on
2296     * independent containers will not interfere with each other's postponement.
2297     * <p>
2298     * Calling postponeEnterTransition on Fragments with a null View will not postpone the
2299     * transition. Likewise, postponement only works if FragmentTransaction optimizations are
2300     * enabled.
2301     *
2302     * @see Activity#postponeEnterTransition()
2303     * @see FragmentTransaction#setAllowOptimization(boolean)
2304     */
2305    public void postponeEnterTransition() {
2306        ensureAnimationInfo().mEnterTransitionPostponed = true;
2307    }
2308
2309    /**
2310     * Begin postponed transitions after {@link #postponeEnterTransition()} was called.
2311     * If postponeEnterTransition() was called, you must call startPostponedEnterTransition()
2312     * or {@link FragmentManager#executePendingTransactions()} to complete the FragmentTransaction.
2313     * If postponement was interrupted with {@link FragmentManager#executePendingTransactions()},
2314     * before {@code startPostponedEnterTransition()}, animations may not run or may execute
2315     * improperly.
2316     *
2317     * @see Activity#startPostponedEnterTransition()
2318     */
2319    public void startPostponedEnterTransition() {
2320        if (mFragmentManager == null || mFragmentManager.mHost == null) {
2321                ensureAnimationInfo().mEnterTransitionPostponed = false;
2322        } else if (Looper.myLooper() != mFragmentManager.mHost.getHandler().getLooper()) {
2323            mFragmentManager.mHost.getHandler().
2324                    postAtFrontOfQueue(this::callStartTransitionListener);
2325        } else {
2326            callStartTransitionListener();
2327        }
2328    }
2329
2330    /**
2331     * Calls the start transition listener. This must be called on the UI thread.
2332     */
2333    private void callStartTransitionListener() {
2334        final OnStartEnterTransitionListener listener;
2335        if (mAnimationInfo == null) {
2336            listener = null;
2337        } else {
2338            mAnimationInfo.mEnterTransitionPostponed = false;
2339            listener = mAnimationInfo.mStartEnterTransitionListener;
2340            mAnimationInfo.mStartEnterTransitionListener = null;
2341        }
2342        if (listener != null) {
2343            listener.onStartEnterTransition();
2344        }
2345    }
2346
2347    /**
2348     * Returns true if mAnimationInfo is not null or the transition differs from the default value.
2349     * This is broken out to ensure mAnimationInfo is properly locked when checking.
2350     */
2351    private boolean shouldChangeTransition(Transition transition, Transition defaultValue) {
2352        if (transition == defaultValue) {
2353            return mAnimationInfo != null;
2354        }
2355        return true;
2356    }
2357
2358    /**
2359     * Print the Fragments's state into the given stream.
2360     *
2361     * @param prefix Text to print at the front of each line.
2362     * @param fd The raw file descriptor that the dump is being sent to.
2363     * @param writer The PrintWriter to which you should dump your state.  This will be
2364     * closed for you after you return.
2365     * @param args additional arguments to the dump request.
2366     */
2367    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
2368        writer.print(prefix); writer.print("mFragmentId=#");
2369        writer.print(Integer.toHexString(mFragmentId));
2370        writer.print(" mContainerId=#");
2371        writer.print(Integer.toHexString(mContainerId));
2372        writer.print(" mTag="); writer.println(mTag);
2373        writer.print(prefix); writer.print("mState="); writer.print(mState);
2374        writer.print(" mIndex="); writer.print(mIndex);
2375        writer.print(" mWho="); writer.print(mWho);
2376        writer.print(" mBackStackNesting="); writer.println(mBackStackNesting);
2377        writer.print(prefix); writer.print("mAdded="); writer.print(mAdded);
2378        writer.print(" mRemoving="); writer.print(mRemoving);
2379        writer.print(" mFromLayout="); writer.print(mFromLayout);
2380        writer.print(" mInLayout="); writer.println(mInLayout);
2381        writer.print(prefix); writer.print("mHidden="); writer.print(mHidden);
2382        writer.print(" mDetached="); writer.print(mDetached);
2383        writer.print(" mMenuVisible="); writer.print(mMenuVisible);
2384        writer.print(" mHasMenu="); writer.println(mHasMenu);
2385        writer.print(prefix); writer.print("mRetainInstance="); writer.print(mRetainInstance);
2386        writer.print(" mRetaining="); writer.print(mRetaining);
2387        writer.print(" mUserVisibleHint="); writer.println(mUserVisibleHint);
2388        if (mFragmentManager != null) {
2389            writer.print(prefix); writer.print("mFragmentManager=");
2390            writer.println(mFragmentManager);
2391        }
2392        if (mHost != null) {
2393            writer.print(prefix); writer.print("mHost=");
2394            writer.println(mHost);
2395        }
2396        if (mParentFragment != null) {
2397            writer.print(prefix); writer.print("mParentFragment=");
2398            writer.println(mParentFragment);
2399        }
2400        if (mArguments != null) {
2401            writer.print(prefix); writer.print("mArguments="); writer.println(mArguments);
2402        }
2403        if (mSavedFragmentState != null) {
2404            writer.print(prefix); writer.print("mSavedFragmentState=");
2405            writer.println(mSavedFragmentState);
2406        }
2407        if (mSavedViewState != null) {
2408            writer.print(prefix); writer.print("mSavedViewState=");
2409            writer.println(mSavedViewState);
2410        }
2411        if (mTarget != null) {
2412            writer.print(prefix); writer.print("mTarget="); writer.print(mTarget);
2413            writer.print(" mTargetRequestCode=");
2414            writer.println(mTargetRequestCode);
2415        }
2416        if (getNextAnim() != 0) {
2417            writer.print(prefix); writer.print("mNextAnim="); writer.println(getNextAnim());
2418        }
2419        if (mContainer != null) {
2420            writer.print(prefix); writer.print("mContainer="); writer.println(mContainer);
2421        }
2422        if (mView != null) {
2423            writer.print(prefix); writer.print("mView="); writer.println(mView);
2424        }
2425        if (getAnimatingAway() != null) {
2426            writer.print(prefix); writer.print("mAnimatingAway=");
2427            writer.println(getAnimatingAway());
2428            writer.print(prefix); writer.print("mStateAfterAnimating=");
2429            writer.println(getStateAfterAnimating());
2430        }
2431        if (mLoaderManager != null) {
2432            writer.print(prefix); writer.println("Loader Manager:");
2433            mLoaderManager.dump(prefix + "  ", fd, writer, args);
2434        }
2435        if (mChildFragmentManager != null) {
2436            writer.print(prefix); writer.println("Child " + mChildFragmentManager + ":");
2437            mChildFragmentManager.dump(prefix + "  ", fd, writer, args);
2438        }
2439    }
2440
2441    Fragment findFragmentByWho(String who) {
2442        if (who.equals(mWho)) {
2443            return this;
2444        }
2445        if (mChildFragmentManager != null) {
2446            return mChildFragmentManager.findFragmentByWho(who);
2447        }
2448        return null;
2449    }
2450
2451    void instantiateChildFragmentManager() {
2452        mChildFragmentManager = new FragmentManagerImpl();
2453        mChildFragmentManager.attachController(mHost, new FragmentContainer() {
2454            @Override
2455            @Nullable
2456            public View onFindViewById(int id) {
2457                if (mView == null) {
2458                    throw new IllegalStateException("Fragment does not have a view");
2459                }
2460                return mView.findViewById(id);
2461            }
2462
2463            @Override
2464            public boolean onHasView() {
2465                return (mView != null);
2466            }
2467        }, this);
2468    }
2469
2470    void performCreate(Bundle savedInstanceState) {
2471        if (mChildFragmentManager != null) {
2472            mChildFragmentManager.noteStateNotSaved();
2473        }
2474        mState = CREATED;
2475        mCalled = false;
2476        onCreate(savedInstanceState);
2477        if (!mCalled) {
2478            throw new SuperNotCalledException("Fragment " + this
2479                    + " did not call through to super.onCreate()");
2480        }
2481        final Context context = getContext();
2482        final int version = context != null ? context.getApplicationInfo().targetSdkVersion : 0;
2483        if (version < Build.VERSION_CODES.N) {
2484            restoreChildFragmentState(savedInstanceState, false);
2485        }
2486    }
2487
2488    View performCreateView(LayoutInflater inflater, ViewGroup container,
2489            Bundle savedInstanceState) {
2490        if (mChildFragmentManager != null) {
2491            mChildFragmentManager.noteStateNotSaved();
2492        }
2493        mPerformedCreateView = true;
2494        return onCreateView(inflater, container, savedInstanceState);
2495    }
2496
2497    void performActivityCreated(Bundle savedInstanceState) {
2498        if (mChildFragmentManager != null) {
2499            mChildFragmentManager.noteStateNotSaved();
2500        }
2501        mState = ACTIVITY_CREATED;
2502        mCalled = false;
2503        onActivityCreated(savedInstanceState);
2504        if (!mCalled) {
2505            throw new SuperNotCalledException("Fragment " + this
2506                    + " did not call through to super.onActivityCreated()");
2507        }
2508        if (mChildFragmentManager != null) {
2509            mChildFragmentManager.dispatchActivityCreated();
2510        }
2511    }
2512
2513    void performStart() {
2514        if (mChildFragmentManager != null) {
2515            mChildFragmentManager.noteStateNotSaved();
2516            mChildFragmentManager.execPendingActions();
2517        }
2518        mState = STARTED;
2519        mCalled = false;
2520        onStart();
2521        if (!mCalled) {
2522            throw new SuperNotCalledException("Fragment " + this
2523                    + " did not call through to super.onStart()");
2524        }
2525        if (mChildFragmentManager != null) {
2526            mChildFragmentManager.dispatchStart();
2527        }
2528        if (mLoaderManager != null) {
2529            mLoaderManager.doReportStart();
2530        }
2531    }
2532
2533    void performResume() {
2534        if (mChildFragmentManager != null) {
2535            mChildFragmentManager.noteStateNotSaved();
2536            mChildFragmentManager.execPendingActions();
2537        }
2538        mState = RESUMED;
2539        mCalled = false;
2540        onResume();
2541        if (!mCalled) {
2542            throw new SuperNotCalledException("Fragment " + this
2543                    + " did not call through to super.onResume()");
2544        }
2545        if (mChildFragmentManager != null) {
2546            mChildFragmentManager.dispatchResume();
2547            mChildFragmentManager.execPendingActions();
2548        }
2549    }
2550
2551    void performMultiWindowModeChanged(boolean isInMultiWindowMode) {
2552        onMultiWindowModeChanged(isInMultiWindowMode);
2553        if (mChildFragmentManager != null) {
2554            mChildFragmentManager.dispatchMultiWindowModeChanged(isInMultiWindowMode);
2555        }
2556    }
2557
2558    void performPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
2559        onPictureInPictureModeChanged(isInPictureInPictureMode);
2560        if (mChildFragmentManager != null) {
2561            mChildFragmentManager.dispatchPictureInPictureModeChanged(isInPictureInPictureMode);
2562        }
2563    }
2564
2565    void performConfigurationChanged(Configuration newConfig) {
2566        onConfigurationChanged(newConfig);
2567        if (mChildFragmentManager != null) {
2568            mChildFragmentManager.dispatchConfigurationChanged(newConfig);
2569        }
2570    }
2571
2572    void performLowMemory() {
2573        onLowMemory();
2574        if (mChildFragmentManager != null) {
2575            mChildFragmentManager.dispatchLowMemory();
2576        }
2577    }
2578
2579    void performTrimMemory(int level) {
2580        onTrimMemory(level);
2581        if (mChildFragmentManager != null) {
2582            mChildFragmentManager.dispatchTrimMemory(level);
2583        }
2584    }
2585
2586    boolean performCreateOptionsMenu(Menu menu, MenuInflater inflater) {
2587        boolean show = false;
2588        if (!mHidden) {
2589            if (mHasMenu && mMenuVisible) {
2590                show = true;
2591                onCreateOptionsMenu(menu, inflater);
2592            }
2593            if (mChildFragmentManager != null) {
2594                show |= mChildFragmentManager.dispatchCreateOptionsMenu(menu, inflater);
2595            }
2596        }
2597        return show;
2598    }
2599
2600    boolean performPrepareOptionsMenu(Menu menu) {
2601        boolean show = false;
2602        if (!mHidden) {
2603            if (mHasMenu && mMenuVisible) {
2604                show = true;
2605                onPrepareOptionsMenu(menu);
2606            }
2607            if (mChildFragmentManager != null) {
2608                show |= mChildFragmentManager.dispatchPrepareOptionsMenu(menu);
2609            }
2610        }
2611        return show;
2612    }
2613
2614    boolean performOptionsItemSelected(MenuItem item) {
2615        if (!mHidden) {
2616            if (mHasMenu && mMenuVisible) {
2617                if (onOptionsItemSelected(item)) {
2618                    return true;
2619                }
2620            }
2621            if (mChildFragmentManager != null) {
2622                if (mChildFragmentManager.dispatchOptionsItemSelected(item)) {
2623                    return true;
2624                }
2625            }
2626        }
2627        return false;
2628    }
2629
2630    boolean performContextItemSelected(MenuItem item) {
2631        if (!mHidden) {
2632            if (onContextItemSelected(item)) {
2633                return true;
2634            }
2635            if (mChildFragmentManager != null) {
2636                if (mChildFragmentManager.dispatchContextItemSelected(item)) {
2637                    return true;
2638                }
2639            }
2640        }
2641        return false;
2642    }
2643
2644    void performOptionsMenuClosed(Menu menu) {
2645        if (!mHidden) {
2646            if (mHasMenu && mMenuVisible) {
2647                onOptionsMenuClosed(menu);
2648            }
2649            if (mChildFragmentManager != null) {
2650                mChildFragmentManager.dispatchOptionsMenuClosed(menu);
2651            }
2652        }
2653    }
2654
2655    void performSaveInstanceState(Bundle outState) {
2656        onSaveInstanceState(outState);
2657        if (mChildFragmentManager != null) {
2658            Parcelable p = mChildFragmentManager.saveAllState();
2659            if (p != null) {
2660                outState.putParcelable(Activity.FRAGMENTS_TAG, p);
2661            }
2662        }
2663    }
2664
2665    void performPause() {
2666        if (mChildFragmentManager != null) {
2667            mChildFragmentManager.dispatchPause();
2668        }
2669        mState = STARTED;
2670        mCalled = false;
2671        onPause();
2672        if (!mCalled) {
2673            throw new SuperNotCalledException("Fragment " + this
2674                    + " did not call through to super.onPause()");
2675        }
2676    }
2677
2678    void performStop() {
2679        if (mChildFragmentManager != null) {
2680            mChildFragmentManager.dispatchStop();
2681        }
2682        mState = STOPPED;
2683        mCalled = false;
2684        onStop();
2685        if (!mCalled) {
2686            throw new SuperNotCalledException("Fragment " + this
2687                    + " did not call through to super.onStop()");
2688        }
2689
2690        if (mLoadersStarted) {
2691            mLoadersStarted = false;
2692            if (!mCheckedForLoaderManager) {
2693                mCheckedForLoaderManager = true;
2694                mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, false);
2695            }
2696            if (mLoaderManager != null) {
2697                if (mHost.getRetainLoaders()) {
2698                    mLoaderManager.doRetain();
2699                } else {
2700                    mLoaderManager.doStop();
2701                }
2702            }
2703        }
2704    }
2705
2706    void performDestroyView() {
2707        if (mChildFragmentManager != null) {
2708            mChildFragmentManager.dispatchDestroyView();
2709        }
2710        mState = CREATED;
2711        mCalled = false;
2712        onDestroyView();
2713        if (!mCalled) {
2714            throw new SuperNotCalledException("Fragment " + this
2715                    + " did not call through to super.onDestroyView()");
2716        }
2717        if (mLoaderManager != null) {
2718            mLoaderManager.doReportNextStart();
2719        }
2720        mPerformedCreateView = false;
2721    }
2722
2723    void performDestroy() {
2724        if (mChildFragmentManager != null) {
2725            mChildFragmentManager.dispatchDestroy();
2726        }
2727        mState = INITIALIZING;
2728        mCalled = false;
2729        onDestroy();
2730        if (!mCalled) {
2731            throw new SuperNotCalledException("Fragment " + this
2732                    + " did not call through to super.onDestroy()");
2733        }
2734        mChildFragmentManager = null;
2735    }
2736
2737    void performDetach() {
2738        mCalled = false;
2739        onDetach();
2740        if (!mCalled) {
2741            throw new SuperNotCalledException("Fragment " + this
2742                    + " did not call through to super.onDetach()");
2743        }
2744
2745        // Destroy the child FragmentManager if we still have it here.
2746        // We won't unless we're retaining our instance and if we do,
2747        // our child FragmentManager instance state will have already been saved.
2748        if (mChildFragmentManager != null) {
2749            if (!mRetaining) {
2750                throw new IllegalStateException("Child FragmentManager of " + this + " was not "
2751                        + " destroyed and this fragment is not retaining instance");
2752            }
2753            mChildFragmentManager.dispatchDestroy();
2754            mChildFragmentManager = null;
2755        }
2756    }
2757
2758    void setOnStartEnterTransitionListener(OnStartEnterTransitionListener listener) {
2759        ensureAnimationInfo();
2760        if (listener == mAnimationInfo.mStartEnterTransitionListener) {
2761            return;
2762        }
2763        if (listener != null && mAnimationInfo.mStartEnterTransitionListener != null) {
2764            throw new IllegalStateException("Trying to set a replacement " +
2765                    "startPostponedEnterTransition on " + this);
2766        }
2767        if (mAnimationInfo.mEnterTransitionPostponed) {
2768            mAnimationInfo.mStartEnterTransitionListener = listener;
2769        }
2770        if (listener != null) {
2771            listener.startListening();
2772        }
2773    }
2774
2775    private static Transition loadTransition(Context context, TypedArray typedArray,
2776            Transition currentValue, Transition defaultValue, int id) {
2777        if (currentValue != defaultValue) {
2778            return currentValue;
2779        }
2780        int transitionId = typedArray.getResourceId(id, 0);
2781        Transition transition = defaultValue;
2782        if (transitionId != 0 && transitionId != com.android.internal.R.transition.no_transition) {
2783            TransitionInflater inflater = TransitionInflater.from(context);
2784            transition = inflater.inflateTransition(transitionId);
2785            if (transition instanceof TransitionSet &&
2786                    ((TransitionSet)transition).getTransitionCount() == 0) {
2787                transition = null;
2788            }
2789        }
2790        return transition;
2791    }
2792
2793    private AnimationInfo ensureAnimationInfo() {
2794        if (mAnimationInfo == null) {
2795            mAnimationInfo = new AnimationInfo();
2796        }
2797        return mAnimationInfo;
2798    }
2799
2800    int getNextAnim() {
2801        if (mAnimationInfo == null) {
2802            return 0;
2803        }
2804        return mAnimationInfo.mNextAnim;
2805    }
2806
2807    void setNextAnim(int animResourceId) {
2808        if (mAnimationInfo == null && animResourceId == 0) {
2809            return; // no change!
2810        }
2811        ensureAnimationInfo().mNextAnim = animResourceId;
2812    }
2813
2814    int getNextTransition() {
2815        if (mAnimationInfo == null) {
2816            return 0;
2817        }
2818        return mAnimationInfo.mNextTransition;
2819    }
2820
2821    void setNextTransition(int nextTransition, int nextTransitionStyle) {
2822        if (mAnimationInfo == null && nextTransition == 0 && nextTransitionStyle == 0) {
2823            return; // no change!
2824        }
2825        ensureAnimationInfo();
2826        mAnimationInfo.mNextTransition = nextTransition;
2827        mAnimationInfo.mNextTransitionStyle = nextTransitionStyle;
2828    }
2829
2830    int getNextTransitionStyle() {
2831        if (mAnimationInfo == null) {
2832            return 0;
2833        }
2834        return mAnimationInfo.mNextTransitionStyle;
2835    }
2836
2837    SharedElementCallback getEnterTransitionCallback() {
2838        if (mAnimationInfo == null) {
2839            return SharedElementCallback.NULL_CALLBACK;
2840        }
2841        return mAnimationInfo.mEnterTransitionCallback;
2842    }
2843
2844    SharedElementCallback getExitTransitionCallback() {
2845        if (mAnimationInfo == null) {
2846            return SharedElementCallback.NULL_CALLBACK;
2847        }
2848        return mAnimationInfo.mExitTransitionCallback;
2849    }
2850
2851    Animator getAnimatingAway() {
2852        if (mAnimationInfo == null) {
2853            return null;
2854        }
2855        return mAnimationInfo.mAnimatingAway;
2856    }
2857
2858    void setAnimatingAway(Animator animator) {
2859        ensureAnimationInfo().mAnimatingAway = animator;
2860    }
2861
2862    int getStateAfterAnimating() {
2863        if (mAnimationInfo == null) {
2864            return 0;
2865        }
2866        return mAnimationInfo.mStateAfterAnimating;
2867    }
2868
2869    void setStateAfterAnimating(int state) {
2870        ensureAnimationInfo().mStateAfterAnimating = state;
2871    }
2872
2873    boolean isPostponed() {
2874        if (mAnimationInfo == null) {
2875            return false;
2876        }
2877        return mAnimationInfo.mEnterTransitionPostponed;
2878    }
2879
2880    boolean isHideReplaced() {
2881        if (mAnimationInfo == null) {
2882            return false;
2883        }
2884        return mAnimationInfo.mIsHideReplaced;
2885    }
2886
2887    void setHideReplaced(boolean replaced) {
2888        ensureAnimationInfo().mIsHideReplaced = replaced;
2889    }
2890
2891    /**
2892     * Used internally to be notified when {@link #startPostponedEnterTransition()} has
2893     * been called. This listener will only be called once and then be removed from the
2894     * listeners.
2895     */
2896    interface OnStartEnterTransitionListener {
2897        void onStartEnterTransition();
2898        void startListening();
2899    }
2900
2901    /**
2902     * Contains all the animation and transition information for a fragment. This will only
2903     * be instantiated for Fragments that have Views.
2904     */
2905    static class AnimationInfo {
2906        // Non-null if the fragment's view hierarchy is currently animating away,
2907        // meaning we need to wait a bit on completely destroying it.  This is the
2908        // animation that is running.
2909        Animator mAnimatingAway;
2910
2911        // If mAnimatingAway != null, this is the state we should move to once the
2912        // animation is done.
2913        int mStateAfterAnimating;
2914
2915        // If app has requested a specific animation, this is the one to use.
2916        int mNextAnim;
2917
2918        // If app has requested a specific transition, this is the one to use.
2919        int mNextTransition;
2920
2921        // If app has requested a specific transition style, this is the one to use.
2922        int mNextTransitionStyle;
2923
2924        private Transition mEnterTransition = null;
2925        private Transition mReturnTransition = USE_DEFAULT_TRANSITION;
2926        private Transition mExitTransition = null;
2927        private Transition mReenterTransition = USE_DEFAULT_TRANSITION;
2928        private Transition mSharedElementEnterTransition = null;
2929        private Transition mSharedElementReturnTransition = USE_DEFAULT_TRANSITION;
2930        private Boolean mAllowReturnTransitionOverlap;
2931        private Boolean mAllowEnterTransitionOverlap;
2932
2933        SharedElementCallback mEnterTransitionCallback = SharedElementCallback.NULL_CALLBACK;
2934        SharedElementCallback mExitTransitionCallback = SharedElementCallback.NULL_CALLBACK;
2935
2936        // True when postponeEnterTransition has been called and startPostponeEnterTransition
2937        // hasn't been called yet.
2938        boolean mEnterTransitionPostponed;
2939
2940        // Listener to wait for startPostponeEnterTransition. After being called, it will
2941        // be set to null
2942        OnStartEnterTransitionListener mStartEnterTransitionListener;
2943
2944        // True if the View was hidden, but the transition is handling the hide
2945        boolean mIsHideReplaced;
2946    }
2947}
2948