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