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