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