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