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