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