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