OSDN Git Service

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