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