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