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