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