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