{% setvar book_path %}/reference/androidx/_book.yaml{% endsetvar %} {% include "_shared/_reference-head-tags.html" %}
public class Fragment
DialogFragment |
Static library support version of the framework's android.app.DialogFragment. |
ListFragment |
Static library support version of the framework's android.app.ListFragment. |
Static library support version of the framework's android.app.Fragment. Used to write apps that run on platforms prior to Android 3.0. When running on Android 3.0 or above, this implementation is still used; it does not try to switch to the framework's implementation. See the framework android.app.Fragment documentation for a class overview.
The main differences when using this support version instead of the framework version are:
FragmentActivity
FragmentActivity#getSupportFragmentManager
to get the FragmentManager
Nested types |
|
---|---|
Fragment.InstantiationException |
Thrown by |
Fragment.SavedState |
State information that has been retrieved from a fragment instance through |
Public constructors |
|
---|---|
Fragment() Constructor used by the default |
|
Alternate constructor that can be called from your default, no argument constructor to provide a default layout that will be inflated by |
Public methods |
|
---|---|
@NonNull void |
dump( Print the Fragments's state into the given stream. |
final @NonNull boolean |
Subclasses can not override equals(). |
final @Nullable FragmentActivity |
Return the |
@NonNull boolean |
Returns whether the the exit transition and enter transition overlap or not. |
@NonNull boolean |
Returns whether the the return transition and reenter transition overlap or not. |
final @Nullable Bundle |
Return the arguments supplied when the fragment was instantiated, if any. |
final @NonNull FragmentManager |
Return a private FragmentManager for placing and managing Fragments inside of this Fragment. |
@Nullable Context |
Return the Context this fragment is currently associated with. |
@NonNull Factory |
The |
@Nullable Object |
Returns the Transition that will be used to move Views into the initial scene. |
@Nullable Object |
Returns the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack. |
final @Nullable FragmentManager |
This method is deprecated. This has been removed in favor of |
final @Nullable Object |
getHost() Return the host object of this fragment. |
final @NonNull int |
getId() Return the identifier this fragment is known by. |
final @NonNull LayoutInflater |
Returns the cached LayoutInflater used to inflate Views of this Fragment. |
@NonNull Lifecycle |
Overriding this method is no longer supported and this method will be made |
@NonNull LoaderManager |
This method is deprecated. Use LoaderManager.getInstance(this). |
final @Nullable Fragment |
Returns the parent Fragment containing this Fragment. |
final @NonNull FragmentManager |
Return the FragmentManager for interacting with fragments associated with this fragment's activity. |
@Nullable Object |
Returns the Transition that will be used to move Views in to the scene when returning due to popping a back stack. |
final @NonNull Resources |
Return |
final @NonNull boolean |
This method is deprecated. Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment. |
@Nullable Object |
Returns the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack. |
final @NonNull SavedStateRegistry |
|
@Nullable Object |
Returns the Transition that will be used for shared elements transferred into the content Scene. |
@Nullable Object |
Return the Transition that will be used for shared elements transferred back during a pop of the back stack. |
final @NonNull String |
Return a localized string from the application's package's default string table. |
final @NonNull String |
Return a localized formatted string from the application's package's default string table, substituting the format arguments as defined in |
final @Nullable String |
getTag() Get the tag name of the fragment, if specified. |
final @Nullable Fragment |
This method is deprecated. Instead of using a target fragment to pass results, use |
final @NonNull int |
This method is deprecated. When using the target fragment replacement of |
final @NonNull CharSequence |
Return a localized, styled CharSequence from the application's package's default string table. |
@NonNull boolean |
This method is deprecated. Use |
@Nullable View |
getView() Get the root view for the fragment's layout (the one returned by |
@NonNull LifecycleOwner |
Get a LifecycleOwner that represents the |
@NonNull LiveData<LifecycleOwner> |
Retrieve a LiveData which allows you to observe the |
@NonNull ViewModelStore |
Returns the ViewModelStore associated with this Fragment |
final @NonNull int |
hashCode() Subclasses can not override hashCode(). |
static @NonNull Fragment |
This method is deprecated. Use |
static @NonNull Fragment |
This method is deprecated. Use |
final @NonNull boolean |
isAdded() Return true if the fragment is currently added to its activity. |
final @NonNull boolean |
Return true if the fragment has been explicitly detached from the UI. |
final @NonNull boolean |
isHidden() Return true if the fragment has been hidden. |
final @NonNull boolean |
Return true if the layout is included as part of an activity view hierarchy via the <fragment> tag. |
final @NonNull boolean |
Return true if this fragment is currently being removed from its activity. |
final @NonNull boolean |
Return true if the fragment is in the resumed state. |
final @NonNull boolean |
Returns true if this fragment is added and its state has already been saved by its host. |
final @NonNull boolean |
Return true if the fragment is currently visible to the user. |
@NonNull void |
This method is deprecated. use |
@NonNull void |
This method is deprecated. use |
@NonNull void |
Called when a fragment is first attached to its context. |
@NonNull void |
This method is deprecated. See |
@NonNull void |
This method is deprecated. The responsibility for listening for fragments being attached has been moved to FragmentManager. |
@NonNull void |
onConfigurationChanged(@NonNull Configuration newConfig) |
@NonNull boolean |
onContextItemSelected(@NonNull MenuItem item) This hook is called whenever an item in a context menu is selected. |
@NonNull void |
Called to do initial creation of a fragment. |
@Nullable Animation |
onCreateAnimation( Called when a fragment loads an animation. |
@Nullable Animator |
onCreateAnimator( Called when a fragment loads an animator. |
@NonNull void |
onCreateContextMenu( Called when a context menu for the |
@NonNull void |
onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) Initialize the contents of the Fragment host's standard options menu. |
@Nullable View |
onCreateView( Called to have the fragment instantiate its user interface view. |
@NonNull void |
Called when the fragment is no longer in use. |
@NonNull void |
Called when this fragment's option menu items are no longer being included in the overall options menu. |
@NonNull void |
Called when the view previously created by |
@NonNull void |
onDetach() Called when the fragment is no longer attached to its activity. |
@NonNull LayoutInflater |
onGetLayoutInflater(@Nullable Bundle savedInstanceState) Returns the LayoutInflater used to inflate Views of this Fragment. |
@NonNull void |
onHiddenChanged(@NonNull boolean hidden) Called when the hidden state (as returned by |
@NonNull void |
onInflate( Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity. |
@NonNull void |
This method is deprecated. See |
@NonNull void |
|
@NonNull void |
onMultiWindowModeChanged(@NonNull boolean isInMultiWindowMode) Called when the Fragment's activity changes from fullscreen mode to multi-window mode and visa-versa. |
@NonNull boolean |
onOptionsItemSelected(@NonNull MenuItem item) This hook is called whenever an item in your options menu is selected. |
@NonNull void |
onOptionsMenuClosed(@NonNull Menu menu) This hook is called whenever the options menu is being closed (either by the user canceling the menu with the back/menu button, or when an item is selected). |
@NonNull void |
onPause() Called when the Fragment is no longer resumed. |
@NonNull void |
onPictureInPictureModeChanged(@NonNull boolean isInPictureInPictureMode) Called by the system when the activity changes to and from picture-in-picture mode. |
@NonNull void |
onPrepareOptionsMenu(@NonNull Menu menu) Prepare the Fragment host's standard options menu to be displayed. |
@NonNull void |
onPrimaryNavigationFragmentChanged( Callback for when the primary navigation state of this Fragment has changed. |
@NonNull void |
This method is deprecated. use |
@NonNull void |
onResume() Called when the fragment is visible to the user and actively running. |
@NonNull void |
onSaveInstanceState(@NonNull Bundle outState) Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance if its process is restarted. |
@NonNull void |
onStart() Called when the Fragment is visible to the user. |
@NonNull void |
onStop() Called when the Fragment is no longer started. |
@NonNull void |
onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) Called immediately after |
@NonNull void |
onViewStateRestored(@Nullable Bundle savedInstanceState) Called when all saved state has been restored into the view hierarchy of the fragment. |
@NonNull void |
Postpone the entering Fragment transition until |
final @NonNull void |
postponeEnterTransition(@NonNull long duration, @NonNull TimeUnit timeUnit) Postpone the entering Fragment transition for a given amount of time and then call |
final @NonNull ActivityResultLauncher<I> |
<I, O> registerForActivityResult( If the host of this fragment is an ActivityResultRegistryOwner the ActivityResultRegistry of the host will be used. |
final @NonNull ActivityResultLauncher<I> |
<I, O> registerForActivityResult( |
@NonNull void |
registerForContextMenu(@NonNull View view) Registers a context menu to be shown for the given view (multiple views can show the context menu). |
final @NonNull void |
This method is deprecated. use |
final @NonNull FragmentActivity |
Return the |
final @NonNull Bundle |
Return the arguments supplied when the fragment was instantiated. |
final @NonNull Context |
Return the Context this fragment is currently associated with. |
final @NonNull FragmentManager |
This method is deprecated. This has been renamed to |
final @NonNull Object |
Return the host object of this fragment. |
final @NonNull Fragment |
Returns the parent Fragment containing this Fragment. |
final @NonNull View |
Get the root view for the fragment's layout (the one returned by |
@NonNull void |
setAllowEnterTransitionOverlap(@NonNull boolean allow) Sets whether the the exit transition and enter transition overlap or not. |
@NonNull void |
setAllowReturnTransitionOverlap(@NonNull boolean allow) Sets whether the the return transition and reenter transition overlap or not. |
@NonNull void |
setArguments(@Nullable Bundle args) Supply the construction arguments for this fragment. |
@NonNull void |
setEnterSharedElementCallback(@Nullable SharedElementCallback callback) When custom transitions are used with Fragments, the enter transition callback is called when this Fragment is attached or detached when not popping the back stack. |
@NonNull void |
setEnterTransition(@Nullable Object transition) Sets the Transition that will be used to move Views into the initial scene. |
@NonNull void |
setExitSharedElementCallback(@Nullable SharedElementCallback callback) When custom transitions are used with Fragments, the exit transition callback is called when this Fragment is attached or detached when popping the back stack. |
@NonNull void |
setExitTransition(@Nullable Object transition) Sets the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack. |
@NonNull void |
setHasOptionsMenu(@NonNull boolean hasMenu) Report that this fragment would like to participate in populating the options menu by receiving a call to |
@NonNull void |
Set the initial saved state that this Fragment should restore itself from when first being constructed, as returned by |
@NonNull void |
setMenuVisibility(@NonNull boolean menuVisible) Set a hint for whether this fragment's menu should be visible. |
@NonNull void |
setReenterTransition(@Nullable Object transition) Sets the Transition that will be used to move Views in to the scene when returning due to popping a back stack. |
@NonNull void |
This method is deprecated. Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment. |
@NonNull void |
setReturnTransition(@Nullable Object transition) Sets the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack. |
@NonNull void |
setSharedElementEnterTransition(@Nullable Object transition) Sets the Transition that will be used for shared elements transferred into the content Scene. |
@NonNull void |
setSharedElementReturnTransition(@Nullable Object transition) Sets the Transition that will be used for shared elements transferred back during a pop of the back stack. |
@NonNull void |
This method is deprecated. Instead of using a target fragment to pass results, the fragment requesting a result should use |
@NonNull void |
This method is deprecated. If you are manually calling this method, use |
@NonNull boolean |
shouldShowRequestPermissionRationale(@NonNull String permission) Gets whether you should show UI with rationale before requesting a permission. |
@NonNull void |
startActivity(@NonNull Intent intent) Call Activity#startActivity(Intent) from the fragment's containing Activity. |
@NonNull void |
startActivity(@NonNull Intent intent, @Nullable Bundle options) Call Activity#startActivity(Intent, Bundle) from the fragment's containing Activity. |
@NonNull void |
This method is deprecated. use |
@NonNull void |
This method is deprecated. use |
@NonNull void |
This method is deprecated. use |
@NonNull void |
Begin postponed transitions after |
@NonNull String |
toString() |
@NonNull void |
unregisterForContextMenu(@NonNull View view) Prevents a context menu to be shown for the given view. |
@NonNull
public Fragment()
Constructor used by the default FragmentFactory
. You must set a custom FragmentFactory
if you want to use a non-default constructor to ensure that your constructor is called when the fragment is re-instantiated.
It is strongly recommended to supply arguments with setArguments
and later retrieved by the Fragment with getArguments
. These arguments are automatically saved and restored alongside the Fragment.
Applications should generally not implement a constructor. Prefer onAttach
instead. It is the first place application code can run where the fragment is ready to be used - the point where the fragment is actually associated with its context. Some applications may also want to implement onInflate to retrieve attributes from a layout resource, although note this happens when the fragment is attached.
@NonNull
public Fragment(@NonNull int contentLayoutId)
Alternate constructor that can be called from your default, no argument constructor to provide a default layout that will be inflated by onCreateView
.
class MyFragment extends Fragment { public MyFragment() { super(R.layout.fragment_main); } }You must
set a custom FragmentFactory
if you want to use a non-default constructor to ensure that your constructor is called when the fragment is re-instantiated.
See also | |
---|---|
Fragment |
#Fragment() |
onCreateView |
#onCreateView(LayoutInflater, ViewGroup, Bundle) |
@NonNull
public void dump(
@NonNull String prefix,
@Nullable FileDescriptor fd,
@NonNull PrintWriter writer,
@Nullable Array<@NonNull String> args
)
Print the Fragments's state into the given stream.
Parameters | |
---|---|
@NonNull String prefix |
Text to print at the front of each line. |
@Nullable FileDescriptor fd |
The raw file descriptor that the dump is being sent to. |
@NonNull PrintWriter writer |
The PrintWriter to which you should dump your state. This will be closed for you after you return. |
@Nullable Array<@NonNull String> args |
additional arguments to the dump request. |
@NonNull
public final boolean equals(@Nullable Object o)
Subclasses can not override equals().
@Nullable
@NonNull
public final FragmentActivity getActivity()
Return the FragmentActivity
this fragment is currently associated with. May return {@code null}
if the fragment is associated with a Context instead.
See also | |
---|---|
requireActivity |
#requireActivity() |
@NonNull
public boolean getAllowEnterTransitionOverlap()
Returns whether the the exit transition and enter transition overlap or not. When true, the enter transition will start as soon as possible. When false, the enter transition will wait until the exit transition completes before starting.
Returns | |
---|---|
boolean |
true when the enter transition should start as soon as possible or false to when it should wait until the exiting transition completes. |
@NonNull
public boolean getAllowReturnTransitionOverlap()
Returns whether the the return transition and reenter transition overlap or not. When true, the reenter transition will start as soon as possible. When false, the reenter transition will wait until the return transition completes before starting.
Returns | |
---|---|
boolean |
true to start the reenter transition when possible or false to wait until the return transition completes. |
@Nullable
@NonNull
public final Bundle getArguments()
Return the arguments supplied when the fragment was instantiated, if any.
@NonNull
public final FragmentManager getChildFragmentManager()
Return a private FragmentManager for placing and managing Fragments inside of this Fragment.
@Nullable
@NonNull
public Context getContext()
Return the Context this fragment is currently associated with.
See also | |
---|---|
requireContext |
#requireContext() |
@NonNull
public Factory getDefaultViewModelProviderFactory()
The Fragment's arguments
when this is first called will be used as the defaults to any androidx.lifecycle.SavedStateHandle passed to a view model created using this factory.
@Nullable
@NonNull
public Object getEnterTransition()
Returns the Transition that will be used to move Views into the initial scene. The entering Views will be those that are regular Views or ViewGroups that have ViewGroup#isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as entering is governed by changing visibility from View#INVISIBLE to View#VISIBLE.
Returns | |
---|---|
Object |
the Transition to use to move Views into the initial Scene. |
@Nullable
@NonNull
public Object getExitTransition()
Returns the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack. The exiting Views will be those that are regular Views or ViewGroups that have ViewGroup#isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as exiting is governed by changing visibility from View#VISIBLE to View#INVISIBLE. If transition is null, the views will remain unaffected.
Returns | |
---|---|
Object |
the Transition to use to move Views out of the Scene when the Fragment is being closed not due to popping the back stack. |
@Nullable
@NonNull
public final FragmentManagergetFragmentManager()
Return the FragmentManager for interacting with fragments associated with this fragment's activity. Note that this will be non-null slightly before getActivity
, during the time from when the fragment is placed in a FragmentTransaction
until it is committed and attached to its activity.
If this Fragment is a child of another Fragment, the FragmentManager returned here will be the parent's getChildFragmentManager
.
See also | |
---|---|
getParentFragmentManager |
#getParentFragmentManager() |
@Nullable
@NonNull
public final Object getHost()
Return the host object of this fragment. May return {@code null}
if the fragment isn't currently being hosted.
See also | |
---|---|
requireHost |
#requireHost() |
@NonNull
public final int getId()
Return the identifier this fragment is known by. This is either the android:id value supplied in a layout or the container view ID supplied when adding the fragment.
@NonNull
public final LayoutInflater getLayoutInflater()
Returns the cached LayoutInflater used to inflate Views of this Fragment. If onGetLayoutInflater
has not been called onGetLayoutInflater
will be called with a {@code null}
argument and that value will be cached.
The cached LayoutInflater will be replaced immediately prior to onCreateView
and cleared immediately after onDetach
.
Returns | |
---|---|
LayoutInflater |
The LayoutInflater used to inflate Views of this Fragment. |
@NonNull
public Lifecycle getLifecycle()
Overriding this method is no longer supported and this method will be made final
in a future version of Fragment.
@NonNull
public LoaderManagergetLoaderManager()
Return the LoaderManager for this fragment.
@Nullable
@NonNull
public final Fragment getParentFragment()
Returns the parent Fragment containing this Fragment. If this Fragment is attached directly to an Activity, returns null.
@NonNull
public final FragmentManager getParentFragmentManager()
Return the FragmentManager for interacting with fragments associated with this fragment's activity. Note that this will be available slightly before getActivity
, during the time from when the fragment is placed in a FragmentTransaction
until it is committed and attached to its activity.
If this Fragment is a child of another Fragment, the FragmentManager returned here will be the parent's getChildFragmentManager
.
Throws | |
---|---|
java.lang.IllegalStateException |
if not associated with a transaction or host. |
@Nullable
@NonNull
public Object getReenterTransition()
Returns the Transition that will be used to move Views in to the scene when returning due to popping a back stack. The entering Views will be those that are regular Views or ViewGroups that have ViewGroup#isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as exiting is governed by changing visibility from View#VISIBLE to View#INVISIBLE. If nothing is set, the default will be to use the same transition as getExitTransition
.
Returns | |
---|---|
Object |
the Transition to use to move Views into the scene when reentering from a previously-started Activity due to popping the back stack. |
@NonNull
public final booleangetRetainInstance()
Returns true
if this fragment instance's state will be retained across configuration changes, and false
if it will not.
Returns | |
---|---|
boolean |
whether or not this fragment instance will be retained. |
See also | |
---|---|
setRetainInstance |
#setRetainInstance(boolean) |
@Nullable
@NonNull
public Object getReturnTransition()
Returns the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack. The exiting Views will be those that are regular Views or ViewGroups that have ViewGroup#isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as entering is governed by changing visibility from View#VISIBLE to View#INVISIBLE. If nothing is set, the default will be to use the same transition as getEnterTransition
.
Returns | |
---|---|
Object |
the Transition to use to move Views out of the Scene when the Fragment is preparing to close due to popping the back stack. |
@Nullable
@NonNull
public Object getSharedElementEnterTransition()
Returns the Transition that will be used for shared elements transferred into the content Scene. Typical Transitions will affect size and location, such as android.transition.ChangeBounds. A null value will cause transferred shared elements to blink to the final position.
Returns | |
---|---|
Object |
The Transition to use for shared elements transferred into the content Scene. |
@Nullable
@NonNull
public Object getSharedElementReturnTransition()
Return the Transition that will be used for shared elements transferred back during a pop of the back stack. This Transition acts in the leaving Fragment. Typical Transitions will affect size and location, such as android.transition.ChangeBounds. A null value will cause transferred shared elements to blink to the final position. If no value is set, the default will be to use the same value as setSharedElementEnterTransition
.
Returns | |
---|---|
Object |
The Transition to use for shared elements transferred out of the content Scene. |
@NonNull
public final String getString(@NonNull int resId)
Return a localized string from the application's package's default string table.
Parameters | |
---|---|
@NonNull int resId |
Resource id for the string |
@NonNull
public final String getString(@NonNull int resId, @Nullable Array<@NonNull Object> formatArgs)
Return a localized formatted string from the application's package's default string table, substituting the format arguments as defined in java.util.Formatter
and format.
@Nullable
@NonNull
public final String getTag()
Get the tag name of the fragment, if specified.
@Nullable
@NonNull
public final FragmentgetTargetFragment()
Return the target fragment set by setTargetFragment
.
@NonNull
public final intgetTargetRequestCode()
Return the target request code set by setTargetFragment
.
@NonNull
public final CharSequence getText(@NonNull int resId)
Return a localized, styled CharSequence from the application's package's default string table.
Parameters | |
---|---|
@NonNull int resId |
Resource id for the CharSequence text |
@NonNull
public booleangetUserVisibleHint()
Returns | |
---|---|
boolean |
The current value of the user-visible hint on this fragment. |
See also | |
---|---|
setUserVisibleHint |
#setUserVisibleHint(boolean) |
@Nullable
@NonNull
public View getView()
Get the root view for the fragment's layout (the one returned by onCreateView
), if provided.
Returns | |
---|---|
View |
The fragment's root view, or null if it has no layout. |
@NonNull
public LifecycleOwner getViewLifecycleOwner()
Get a LifecycleOwner that represents the Fragment's View
lifecycle. In most cases, this mirrors the lifecycle of the Fragment itself, but in cases of detached
Fragments, the lifecycle of the Fragment can be considerably longer than the lifecycle of the View itself.
Namely, the lifecycle of the Fragment's View is:
onViewStateRestored
onStart
onResume
onPause
onStop
onDestroyView
onCreateView
under the condition that you must return a non-null view (an IllegalStateException will be thrown if you access the view lifecycle but don't return a non-null view).
The view lifecycle remains valid through the call to onDestroyView
, after which getView
will return null, the view lifecycle will be destroyed, and this method will throw an IllegalStateException. Consider using getViewLifecycleOwnerLiveData
or FragmentTransaction#runOnCommit(Runnable)
to receive a callback for when the Fragment's view lifecycle is available.
This should only be called on the main thread.
Overriding this method is no longer supported and this method will be made final
in a future version of Fragment.
Returns | |
---|---|
LifecycleOwner |
A LifecycleOwner that represents the |
Throws | |
---|---|
java.lang.IllegalStateException |
if the |
@NonNull
public LiveData<LifecycleOwner> getViewLifecycleOwnerLiveData()
Retrieve a LiveData which allows you to observe the lifecycle of the Fragment's View
.
This will be set to the new LifecycleOwner after onCreateView
returns a non-null View and will set to null after onDestroyView
.
Overriding this method is no longer supported and this method will be made final
in a future version of Fragment.
Returns | |
---|---|
LiveData<LifecycleOwner> |
A LiveData that changes in sync with |
@NonNull
public ViewModelStore getViewModelStore()
Returns the ViewModelStore associated with this Fragment
Overriding this method is no longer supported and this method will be made final
in a future version of Fragment.
Returns | |
---|---|
ViewModelStore |
a |
Throws | |
---|---|
java.lang.IllegalStateException |
if called before the Fragment is attached i.e., before onAttach(). |
@NonNull
public static Fragmentinstantiate(@NonNull Context context, @NonNull String fname)
Like instantiate
but with a null argument Bundle.
@NonNull
public static Fragmentinstantiate(
@NonNull Context context,
@NonNull String fname,
@Nullable Bundle args
)
Create a new instance of a Fragment with the given class name. This is the same as calling its empty constructor, setting the ClassLoader
on the supplied arguments, then calling setArguments
.
Parameters | |
---|---|
@NonNull Context context |
The calling context being used to instantiate the fragment. This is currently just used to get its ClassLoader. |
@NonNull String fname |
The class name of the fragment to instantiate. |
@Nullable Bundle args |
Bundle of arguments to supply to the fragment, which it can retrieve with |
Returns | |
---|---|
Fragment |
Returns a new fragment instance. |
Throws | |
---|---|
androidx.fragment.app.Fragment.InstantiationException |
If there is a failure in instantiating the given fragment class. This is a runtime exception; it is not normally expected to happen. |
@NonNull
public final boolean isAdded()
Return true if the fragment is currently added to its activity.
@NonNull
public final boolean isDetached()
Return true if the fragment has been explicitly detached from the UI. That is, FragmentTransaction.detach(Fragment)
has been used on it.
@NonNull
public final boolean isHidden()
Return true if the fragment has been hidden. By default fragments are shown. You can find out about changes to this state with onHiddenChanged
. Note that the hidden state is orthogonal to other states -- that is, to be visible to the user, a fragment must be both started and not hidden.
@NonNull
public final boolean isInLayout()
Return true if the layout is included as part of an activity view hierarchy via the <fragment> tag. This will always be true when fragments are created through the <fragment> tag, exceptin the case where an old fragment is restored from a previous state and it does not appear in the layout of the current state.
@NonNull
public final boolean isRemoving()
Return true if this fragment is currently being removed from its activity. This is not whether its activity is finishing, but rather whether it is in the process of being removed from its activity.
@NonNull
public final boolean isResumed()
Return true if the fragment is in the resumed state. This is true for the duration of onResume
and onPause
as well.
@NonNull
public final boolean isStateSaved()
Returns true if this fragment is added and its state has already been saved by its host. Any operations that would change saved state should not be performed if this method returns true, and some operations such as setArguments
will fail.
Returns | |
---|---|
boolean |
true if this fragment's state has already been saved by its host |
@NonNull
public final boolean isVisible()
Return true if the fragment is currently visible to the user. This means it: (1) has been added, (2) has its view attached to the window, and (3) is not hidden.
@NonNull
public voidonActivityCreated(@Nullable Bundle savedInstanceState)
Called when the fragment's activity has been created and this fragment's view hierarchy instantiated. It can be used to do final initialization once these pieces are in place, such as retrieving views or restoring state. It is also useful for fragments that use setRetainInstance
to retain their instance, as this callback tells the fragment when it is fully associated with the new activity instance. This is called after onCreateView
and before onViewStateRestored
.
Parameters | |
---|---|
@Nullable Bundle savedInstanceState |
If the fragment is being re-created from a previous saved state, this is the state. |
@NonNull
public voidonActivityResult(
@NonNull int requestCode,
@NonNull int resultCode,
@Nullable Intent data
)
Receive the result from a previous call to startActivityForResult
. This follows the related Activity API as described there in Activity#onActivityResult(int, int, Intent).
Parameters | |
---|---|
@NonNull int requestCode |
The integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from. |
@NonNull int resultCode |
The integer result code returned by the child activity through its setResult(). |
@Nullable Intent data |
An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). |
@NonNull
public void onAttach(@NonNull Context context)
Called when a fragment is first attached to its context. onCreate
will be called after this.
@NonNull
public voidonAttach(@NonNull Activity activity)
Called when a fragment is first attached to its activity. onCreate
will be called after this.
@NonNull
public voidonAttachFragment(@NonNull Fragment childFragment)
Called when a fragment is attached as a child of this fragment.
This is called after the attached fragment's onAttach
and before the attached fragment's onCreate
if the fragment has not yet had a previous call to onCreate
.
@NonNull
public boolean onContextItemSelected(@NonNull MenuItem item)
This hook is called whenever an item in a context menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.
Use MenuItem#getMenuInfo() to get extra information set by the View that added this menu item.
Derived classes should call through to the base class for it to perform the default menu handling.
Parameters | |
---|---|
@NonNull MenuItem item |
The context menu item that was selected. |
Returns | |
---|---|
boolean |
boolean Return false to allow normal context menu processing to proceed, true to consume it here. |
@NonNull
public void onCreate(@Nullable Bundle savedInstanceState)
Called to do initial creation of a fragment. This is called after onAttach
and before onCreateView
.
Note that this can be called while the fragment's activity is still in the process of being created. As such, you can not rely on things like the activity's content view hierarchy being initialized at this point. If you want to do work once the activity itself is created, add a androidx.lifecycle.LifecycleObserver on the activity's Lifecycle, removing it when it receives the Lifecycle.State#CREATED callback.
Any restored child fragments will be created before the base Fragment.onCreate
method returns.
Parameters | |
---|---|
@Nullable Bundle savedInstanceState |
If the fragment is being re-created from a previous saved state, this is the state. |
@Nullable
@NonNull
public Animation onCreateAnimation(
@NonNull int transit,
@NonNull boolean enter,
@NonNull int nextAnim
)
Called when a fragment loads an animation. Note that if FragmentTransaction#setCustomAnimations(int, int)
was called with Animator resources instead of Animation resources, {@code nextAnim}
will be an animator resource.
Parameters | |
---|---|
@NonNull int transit |
The value set in |
@NonNull boolean enter |
|
@NonNull int nextAnim |
The resource set in |
@Nullable
@NonNull
public Animator onCreateAnimator(
@NonNull int transit,
@NonNull boolean enter,
@NonNull int nextAnim
)
Called when a fragment loads an animator. This will be called when onCreateAnimation
returns null. Note that if FragmentTransaction#setCustomAnimations(int, int)
was called with Animation resources instead of Animator resources, {@code nextAnim}
will be an animation resource.
Parameters | |
---|---|
@NonNull int transit |
The value set in |
@NonNull boolean enter |
|
@NonNull int nextAnim |
The resource set in |
@NonNull
public void onCreateContextMenu(
@NonNull ContextMenu menu,
@NonNull View v,
@Nullable ContextMenuInfo menuInfo
)
Called when a context menu for the {@code view}
is about to be shown. Unlike onCreateOptionsMenu
, this will be called every time the context menu is about to be shown and should be populated for the view (or item inside the view for AdapterView subclasses, this can be found in the {@code menuInfo}
)).
Use onContextItemSelected
to know when an item has been selected.
The default implementation calls up to Activity.onCreateContextMenu, though you can not call this implementation if you don't want that behavior.
It is not safe to hold onto the context menu after this method returns.
@NonNull
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater)
Initialize the contents of the Fragment host's standard options menu. You should place your menu items in to menu. For this method to be called, you must have first called setHasOptionsMenu
. See Activity.onCreateOptionsMenu for more information.
Parameters | |
---|---|
@NonNull Menu menu |
The options menu in which you place your items. |
See also | |
---|---|
setHasOptionsMenu |
#setHasOptionsMenu |
onPrepareOptionsMenu |
#onPrepareOptionsMenu |
onOptionsItemSelected |
#onOptionsItemSelected |
@Nullable
@NonNull
public View onCreateView(
@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState
)
Called to have the fragment instantiate its user interface view. This is optional, and non-graphical fragments can return null. This will be called between onCreate
and onViewCreated
.
A default View can be returned by calling Fragment
in your constructor. Otherwise, this method returns null.
It is recommended to only inflate the layout in this method and move logic that operates on the returned View to onViewCreated
.
If you return a View from here, you will later be called in onDestroyView
when the view is being released.
Parameters | |
---|---|
@NonNull LayoutInflater inflater |
The LayoutInflater object that can be used to inflate any views in the fragment, |
@Nullable ViewGroup container |
If non-null, this is the parent view that the fragment's UI should be attached to. The fragment should not add the view itself, but this can be used to generate the LayoutParams of the view. |
@Nullable Bundle savedInstanceState |
If non-null, this fragment is being re-constructed from a previous saved state as given here. |
Returns | |
---|---|
View |
Return the View for the fragment's UI, or null. |
@NonNull
public void onDestroy()
Called when the fragment is no longer in use. This is called after onStop
and before onDetach
.
@NonNull
public void onDestroyOptionsMenu()
Called when this fragment's option menu items are no longer being included in the overall options menu. Receiving this call means that the menu needed to be rebuilt, but this fragment's items were not included in the newly built menu (its onCreateOptionsMenu
was not called).
@NonNull
public void onDestroyView()
Called when the view previously created by onCreateView
has been detached from the fragment. The next time the fragment needs to be displayed, a new view will be created. This is called after onStop
and before onDestroy
. It is called regardless of whether onCreateView
returned a non-null view. Internally it is called after the view's state has been saved but before it has been removed from its parent.
@NonNull
public void onDetach()
Called when the fragment is no longer attached to its activity. This is called after onDestroy
.
@NonNull
public LayoutInflater onGetLayoutInflater(@Nullable Bundle savedInstanceState)
Returns the LayoutInflater used to inflate Views of this Fragment. The default implementation will throw an exception if the Fragment is not attached.
Parameters | |
---|---|
@Nullable Bundle savedInstanceState |
If the fragment is being re-created from a previous saved state, this is the state. |
Returns | |
---|---|
LayoutInflater |
The LayoutInflater used to inflate Views of this Fragment. |
@NonNull
public void onHiddenChanged(@NonNull boolean hidden)
Called when the hidden state (as returned by isHidden
of the fragment has changed. Fragments start out not hidden; this will be called whenever the fragment changes state from that.
Parameters | |
---|---|
@NonNull boolean hidden |
True if the fragment is now hidden, false otherwise. |
@NonNull
public void onInflate(
@NonNull Context context,
@NonNull AttributeSet attrs,
@Nullable Bundle savedInstanceState
)
Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity. This may be called immediately after the fragment is created from a FragmentContainerView
in a layout file. Note this is beforethe fragment's onAttach
has been called; all you should do here is parse the attributes and save them away.
This is called the first time the fragment is inflated. If it is being inflated into a new instance with saved state, this method will not be called a second time for the restored state fragment.
Here is a typical implementation of a fragment that can take parameters both through attributes supplied here as well from getArguments
:
public static class MyFragment extends Fragment { CharSequence mLabel; /** * Create a new instance of MyFragment that will be initialized * with the given arguments. */ static MyFragment newInstance(CharSequence label) { MyFragment f = new MyFragment(); Bundle b = new Bundle(); b.putCharSequence("label", label); f.setArguments(b); return f; } /** * Parse attributes during inflation from a view hierarchy into the * arguments we handle. */ @Override public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs, @Nullable Bundle savedInstanceState) { super.onInflate(context, attrs, savedInstanceState); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FragmentArguments); mLabel = a.getText(R.styleable.FragmentArguments_android_label); a.recycle(); } /** * During creation, if arguments have been supplied to the fragment * then parse those out. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); if (args != null) { CharSequence label = args.getCharSequence("label"); if (label != null) { mLabel = label; } } } /** * Create the view for this fragment, using the arguments given to it. */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.hello_world, container, false); View tv = v.findViewById(R.id.text); ((TextView)tv).setText(mLabel != null ? mLabel : "(no label)"); ViewCompat.setBackground( tv, ContextCompat.getDrawable(getContext(), android.R.drawable.gallery_thumb)); return v; } }
Note that parsing the XML attributes uses a "styleable" resource. The declaration for the styleable used here is:
<declare-styleable name="FragmentArguments"> <attr name="android:label" /> </declare-styleable>
The fragment can then be declared within its activity's content layout through a tag like this:
<androidx.fragment.app.FragmentContainerView class="com.example.android.supportv4.app.FragmentArgumentsSupport$MyFragment" android:id="@+id/embedded" android:layout_width="0px" android:layout_height="wrap_content" android:layout_weight="1" android:label="@string/fragment_arguments_embedded" />
This fragment can also be created dynamically from arguments given at runtime in the arguments Bundle; here is an example of doing so at creation of the containing activity:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_arguments_support); if (savedInstanceState == null) { // First-time init; create fragment to embed in activity. FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); Fragment newFragment = MyFragment.newInstance("From Arguments"); ft.add(R.id.created, newFragment); ft.commit(); } }
@NonNull
public voidonInflate(
@NonNull Activity activity,
@NonNull AttributeSet attrs,
@Nullable Bundle savedInstanceState
)
Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity.
@NonNull
public void onMultiWindowModeChanged(@NonNull boolean isInMultiWindowMode)
Called when the Fragment's activity changes from fullscreen mode to multi-window mode and visa-versa. This is generally tied to Activity#onMultiWindowModeChanged of the containing Activity.
Parameters | |
---|---|
@NonNull boolean isInMultiWindowMode |
True if the activity is in multi-window mode. |
@NonNull
public boolean onOptionsItemSelected(@NonNull MenuItem item)
This hook is called whenever an item in your options menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.
Derived classes should call through to the base class for it to perform the default menu handling.
Parameters | |
---|---|
@NonNull MenuItem item |
The menu item that was selected. |
Returns | |
---|---|
boolean |
boolean Return false to allow normal menu processing to proceed, true to consume it here. |
See also | |
---|---|
onCreateOptionsMenu |
#onCreateOptionsMenu |
@NonNull
public void onOptionsMenuClosed(@NonNull Menu menu)
This hook is called whenever the options menu is being closed (either by the user canceling the menu with the back/menu button, or when an item is selected).
Parameters | |
---|---|
@NonNull Menu menu |
The options menu as last shown or first initialized by onCreateOptionsMenu(). |
@NonNull
public void onPause()
Called when the Fragment is no longer resumed. This is generally tied to Activity.onPause of the containing Activity's lifecycle.
@NonNull
public void onPictureInPictureModeChanged(@NonNull boolean isInPictureInPictureMode)
Called by the system when the activity changes to and from picture-in-picture mode. This is generally tied to Activity#onPictureInPictureModeChanged of the containing Activity.
Parameters | |
---|---|
@NonNull boolean isInPictureInPictureMode |
True if the activity is in picture-in-picture mode. |
@NonNull
public void onPrepareOptionsMenu(@NonNull Menu menu)
Prepare the Fragment host's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents. See Activity.onPrepareOptionsMenu for more information.
Parameters | |
---|---|
@NonNull Menu menu |
The options menu as last shown or first initialized by onCreateOptionsMenu(). |
See also | |
---|---|
setHasOptionsMenu |
#setHasOptionsMenu |
onCreateOptionsMenu |
#onCreateOptionsMenu |
@NonNull
public void onPrimaryNavigationFragmentChanged(
@NonNull boolean isPrimaryNavigationFragment
)
Callback for when the primary navigation state of this Fragment has changed. This can be the result of the getParentFragmentManager
containing FragmentManager} having its primary navigation fragment changed via setPrimaryNavigationFragment
or due to the primary navigation fragment changing in a parent FragmentManager.
Parameters | |
---|---|
@NonNull boolean isPrimaryNavigationFragment |
True if and only if this Fragment and any |
@NonNull
public voidonRequestPermissionsResult(
@NonNull int requestCode,
@NonNull Array<@NonNull String> permissions,
@NonNull Array<@NonNull int> grantResults
)
Callback for the result from requesting permissions. This method is invoked for every call on requestPermissions
.
Note: It is possible that the permissions request interaction with the user is interrupted. In this case you will receive empty permissions and results arrays which should be treated as a cancellation.
Parameters | |
---|---|
@NonNull int requestCode |
The request code passed in |
@NonNull Array<@NonNull String> permissions |
The requested permissions. Never null. |
@NonNull Array<@NonNull int> grantResults |
The grant results for the corresponding permissions which is either PERMISSION_GRANTED or PERMISSION_DENIED. Never null. |
See also | |
---|---|
requestPermissions |
#requestPermissions(String[], int) |
@NonNull
public void onResume()
Called when the fragment is visible to the user and actively running. This is generally tied to Activity.onResume of the containing Activity's lifecycle.
@NonNull
public void onSaveInstanceState(@NonNull Bundle outState)
Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance if its process is restarted. If a new instance of the fragment later needs to be created, the data you place in the Bundle here will be available in the Bundle given to onCreate
, onCreateView
, and onViewCreated
.
This corresponds to Activity.onSaveInstanceState(Bundle) and most of the discussion there applies here as well. Note however: this method may be called at any time before onDestroy
. There are many situations where a fragment may be mostly torn down (such as when placed on the back stack with no UI showing), but its state will not be saved until its owning activity actually needs to save its state.
Parameters | |
---|---|
@NonNull Bundle outState |
Bundle in which to place your saved state. |
@NonNull
public void onStart()
Called when the Fragment is visible to the user. This is generally tied to Activity.onStart of the containing Activity's lifecycle.
@NonNull
public void onStop()
Called when the Fragment is no longer started. This is generally tied to Activity.onStop of the containing Activity's lifecycle.
@NonNull
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)
Called immediately after onCreateView
has returned, but before any saved state has been restored in to the view. This gives subclasses a chance to initialize themselves once they know their view hierarchy has been completely created. The fragment's view hierarchy is not however attached to its parent at this point.
Parameters | |
---|---|
@NonNull View view |
The View returned by |
@Nullable Bundle savedInstanceState |
If non-null, this fragment is being re-constructed from a previous saved state as given here. |
@NonNull
public void onViewStateRestored(@Nullable Bundle savedInstanceState)
Called when all saved state has been restored into the view hierarchy of the fragment. This can be used to do initialization based on saved state that you are letting the view hierarchy track itself, such as whether check box widgets are currently checked. This is called after onViewCreated
and before onStart
.
Parameters | |
---|---|
@Nullable Bundle savedInstanceState |
If the fragment is being re-created from a previous saved state, this is the state. |
@NonNull
public void postponeEnterTransition()
Postpone the entering Fragment transition until startPostponedEnterTransition
or FragmentManager#executePendingTransactions()
has been called.
This method gives the Fragment the ability to delay Fragment animations until all data is loaded. Until then, the added, shown, and attached Fragments will be INVISIBLE and removed, hidden, and detached Fragments won't be have their Views removed. The transaction runs when all postponed added Fragments in the transaction have called startPostponedEnterTransition
.
This method should be called before being added to the FragmentTransaction or in onCreate
, onAttach
, or onCreateView
}. startPostponedEnterTransition
must be called to allow the Fragment to start the transitions.
When a FragmentTransaction is started that may affect a postponed FragmentTransaction, based on which containers are in their operations, the postponed FragmentTransaction will have its start triggered. The early triggering may result in faulty or nonexistent animations in the postponed transaction. FragmentTransactions that operate only on independent containers will not interfere with each other's postponement.
Calling postponeEnterTransition on Fragments with a null View will not postpone the transition. Likewise, postponement only works if FragmentTransaction reordering
is enabled if you have called FragmentManager#enableNewStateManager(boolean)
with false
.
See also | |
---|---|
Activity |
android.app.Activity#postponeEnterTransition() |
setReorderingAllowed |
androidx.fragment.app.FragmentTransaction#setReorderingAllowed(boolean) |
@NonNull
public final void postponeEnterTransition(@NonNull long duration, @NonNull TimeUnit timeUnit)
Postpone the entering Fragment transition for a given amount of time and then call startPostponedEnterTransition
.
This method gives the Fragment the ability to delay Fragment animations for a given amount of time. Until then, the added, shown, and attached Fragments will be INVISIBLE and removed, hidden, and detached Fragments won't be have their Views removed. The transaction runs when all postponed added Fragments in the transaction have called startPostponedEnterTransition
.
This method should be called before being added to the FragmentTransaction or in onCreate
, onAttach
, or onCreateView
}.
When a FragmentTransaction is started that may affect a postponed FragmentTransaction, based on which containers are in their operations, the postponed FragmentTransaction will have its start triggered. The early triggering may result in faulty or nonexistent animations in the postponed transaction. FragmentTransactions that operate only on independent containers will not interfere with each other's postponement.
Calling postponeEnterTransition on Fragments with a null View will not postpone the transition. Likewise, postponement only works if FragmentTransaction reordering
is enabled if you have called FragmentManager#enableNewStateManager(boolean)
with false
.
Parameters | |
---|---|
@NonNull long duration |
The length of the delay in |
@NonNull TimeUnit timeUnit |
The units of time for |
See also | |
---|---|
Activity |
android.app.Activity#postponeEnterTransition() |
setReorderingAllowed |
androidx.fragment.app.FragmentTransaction#setReorderingAllowed(boolean) |
@NonNull
public final ActivityResultLauncher<I> <I, O> registerForActivityResult(
@NonNull ActivityResultContract<I, O> contract,
@NonNull ActivityResultCallback<O> callback
)
If the host of this fragment is an ActivityResultRegistryOwner the ActivityResultRegistry of the host will be used. Otherwise, this will use the registry of the Fragment's Activity.
@NonNull
public final ActivityResultLauncher<I> <I, O> registerForActivityResult(
@NonNull ActivityResultContract<I, O> contract,
@NonNull ActivityResultRegistry registry,
@NonNull ActivityResultCallback<O> callback
)
@NonNull
public void registerForContextMenu(@NonNull View view)
Registers a context menu to be shown for the given view (multiple views can show the context menu). This method will set the OnCreateContextMenuListener on the view to this fragment, so onCreateContextMenu
will be called when it is time to show the context menu.
Parameters | |
---|---|
@NonNull View view |
The view that should show a context menu. |
See also | |
---|---|
unregisterForContextMenu |
#unregisterForContextMenu(View) |
@NonNull
public final voidrequestPermissions(
@NonNull Array<@NonNull String> permissions,
@NonNull int requestCode
)
Requests permissions to be granted to this application. These permissions must be requested in your manifest, they should not be granted to your app, and they should have protection level #PROTECTION_DANGEROUS dangerous, regardless whether they are declared by the platform or a third-party app.
Normal permissions PROTECTION_NORMAL are granted at install time if requested in the manifest. Signature permissions PROTECTION_SIGNATURE are granted at install time if requested in the manifest and the signature of your app matches the signature of the app declaring the permissions.
Call shouldShowRequestPermissionRationale
before calling this API to check if the system recommends to show a rationale dialog before asking for a permission.
If your app does not have the requested permissions the user will be presented with UI for accepting them. After the user has accepted or rejected the requested permissions you will receive a callback on reporting whether the permissions were granted or not.
Note that requesting a permission does not guarantee it will be granted and your app should be able to run without having this permission.
This method may start an activity allowing the user to choose which permissions to grant and which to reject. Hence, you should be prepared that your activity may be paused and resumed. Further, granting some permissions may require a restart of you application. In such a case, the system will recreate the activity stack before delivering the result to .
When checking whether you have a permission you should use .
Calling this API for permissions already granted to your app would show UI to the user to decided whether the app can still hold these permissions. This can be useful if the way your app uses the data guarded by the permissions changes significantly.
Parameters | |
---|---|
@NonNull Array<@NonNull String> permissions |
The requested permissions. |
@NonNull int requestCode |
Application specific request code to match with a result reported to |
See also | |
---|---|
onRequestPermissionsResult |
#onRequestPermissionsResult(int, String[], int[]) |
Context |
android.content.Context#checkSelfPermission(String) |
@NonNull
public final FragmentActivity requireActivity()
Return the FragmentActivity
this fragment is currently associated with.
Throws | |
---|---|
java.lang.IllegalStateException |
if not currently associated with an activity or if associated only with a context. |
See also | |
---|---|
getActivity |
#getActivity() |
@NonNull
public final Bundle requireArguments()
Return the arguments supplied when the fragment was instantiated.
Throws | |
---|---|
java.lang.IllegalStateException |
if no arguments were supplied to the Fragment. |
See also | |
---|---|
getArguments |
#getArguments() |
@NonNull
public final Context requireContext()
Return the Context this fragment is currently associated with.
Throws | |
---|---|
java.lang.IllegalStateException |
if not currently associated with a context. |
See also | |
---|---|
getContext |
#getContext() |
@NonNull
public final FragmentManagerrequireFragmentManager()
Return the FragmentManager for interacting with fragments associated with this fragment's activity. Note that this will be available slightly before getActivity
, during the time from when the fragment is placed in a FragmentTransaction
until it is committed and attached to its activity.
If this Fragment is a child of another Fragment, the FragmentManager returned here will be the parent's getChildFragmentManager
.
Throws | |
---|---|
java.lang.IllegalStateException |
if not associated with a transaction or host. |
See also | |
---|---|
getParentFragmentManager |
#getParentFragmentManager() |
@NonNull
public final Object requireHost()
Return the host object of this fragment.
Throws | |
---|---|
java.lang.IllegalStateException |
if not currently associated with a host. |
See also | |
---|---|
getHost |
#getHost() |
@NonNull
public final Fragment requireParentFragment()
Returns the parent Fragment containing this Fragment.
Throws | |
---|---|
java.lang.IllegalStateException |
if this Fragment is attached directly to an Activity or other Fragment host. |
See also | |
---|---|
getParentFragment |
#getParentFragment() |
@NonNull
public final View requireView()
Get the root view for the fragment's layout (the one returned by onCreateView
).
Throws | |
---|---|
java.lang.IllegalStateException |
if no view was returned by |
See also | |
---|---|
getView |
#getView() |
@NonNull
public void setAllowEnterTransitionOverlap(@NonNull boolean allow)
Sets whether the the exit transition and enter transition overlap or not. When true, the enter transition will start as soon as possible. When false, the enter transition will wait until the exit transition completes before starting.
Parameters | |
---|---|
@NonNull boolean allow |
true to start the enter transition when possible or false to wait until the exiting transition completes. |
@NonNull
public void setAllowReturnTransitionOverlap(@NonNull boolean allow)
Sets whether the the return transition and reenter transition overlap or not. When true, the reenter transition will start as soon as possible. When false, the reenter transition will wait until the return transition completes before starting.
Parameters | |
---|---|
@NonNull boolean allow |
true to start the reenter transition when possible or false to wait until the return transition completes. |
@NonNull
public void setArguments(@Nullable Bundle args)
Supply the construction arguments for this fragment. The arguments supplied here will be retained across fragment destroy and creation.
This method cannot be called if the fragment is added to a FragmentManager and if isStateSaved
would return true.
@NonNull
public void setEnterSharedElementCallback(@Nullable SharedElementCallback callback)
When custom transitions are used with Fragments, the enter transition callback is called when this Fragment is attached or detached when not popping the back stack.
Parameters | |
---|---|
@Nullable SharedElementCallback callback |
Used to manipulate the shared element transitions on this Fragment when added not as a pop from the back stack. |
@NonNull
public void setEnterTransition(@Nullable Object transition)
Sets the Transition that will be used to move Views into the initial scene. The entering Views will be those that are regular Views or ViewGroups that have ViewGroup#isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as entering is governed by changing visibility from View#INVISIBLE to View#VISIBLE. If transition
is null, entering Views will remain unaffected.
@NonNull
public void setExitSharedElementCallback(@Nullable SharedElementCallback callback)
When custom transitions are used with Fragments, the exit transition callback is called when this Fragment is attached or detached when popping the back stack.
Parameters | |
---|---|
@Nullable SharedElementCallback callback |
Used to manipulate the shared element transitions on this Fragment when added as a pop from the back stack. |
@NonNull
public void setExitTransition(@Nullable Object transition)
Sets the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack. The exiting Views will be those that are regular Views or ViewGroups that have ViewGroup#isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as exiting is governed by changing visibility from View#VISIBLE to View#INVISIBLE. If transition is null, the views will remain unaffected.
@NonNull
public void setHasOptionsMenu(@NonNull boolean hasMenu)
Report that this fragment would like to participate in populating the options menu by receiving a call to onCreateOptionsMenu
and related methods.
Parameters | |
---|---|
@NonNull boolean hasMenu |
If true, the fragment has menu items to contribute. |
@NonNull
public void setInitialSavedState(@Nullable Fragment.SavedState state)
Set the initial saved state that this Fragment should restore itself from when first being constructed, as returned by FragmentManager.saveFragmentInstanceState
.
Parameters | |
---|---|
@Nullable Fragment.SavedState state |
The state the fragment should be restored from. |
@NonNull
public void setMenuVisibility(@NonNull boolean menuVisible)
Set a hint for whether this fragment's menu should be visible. This is useful if you know that a fragment has been placed in your view hierarchy so that the user can not currently seen it, so any menu items it has should also not be shown.
Parameters | |
---|---|
@NonNull boolean menuVisible |
The default is true, meaning the fragment's menu will be shown as usual. If false, the user will not see the menu. |
@NonNull
public void setReenterTransition(@Nullable Object transition)
Sets the Transition that will be used to move Views in to the scene when returning due to popping a back stack. The entering Views will be those that are regular Views or ViewGroups that have ViewGroup#isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as exiting is governed by changing visibility from View#VISIBLE to View#INVISIBLE. If transition is null, the views will remain unaffected. If nothing is set, the default will be to use the same transition as getExitTransition
.
@NonNull
public voidsetRetainInstance(@NonNull boolean retain)
Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). If set, the fragment lifecycle will be slightly different when an activity is recreated:
onDestroy
will not be called (but onDetach
still will be, because the fragment is being detached from its current activity). onCreate
will not be called since the fragment is not being re-created. onAttach
and onActivityCreated
willstill be called. Parameters | |
---|---|
@NonNull boolean retain |
|
See also | |
---|---|
getRetainInstance |
#getRetainInstance() |
@NonNull
public void setReturnTransition(@Nullable Object transition)
Sets the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack. The exiting Views will be those that are regular Views or ViewGroups that have ViewGroup#isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as entering is governed by changing visibility from View#VISIBLE to View#INVISIBLE. If transition
is null, entering Views will remain unaffected. If nothing is set, the default will be to use the same value as set in setEnterTransition
.
@NonNull
public void setSharedElementEnterTransition(@Nullable Object transition)
Sets the Transition that will be used for shared elements transferred into the content Scene. Typical Transitions will affect size and location, such as android.transition.ChangeBounds. A null value will cause transferred shared elements to blink to the final position.
@NonNull
public void setSharedElementReturnTransition(@Nullable Object transition)
Sets the Transition that will be used for shared elements transferred back during a pop of the back stack. This Transition acts in the leaving Fragment. Typical Transitions will affect size and location, such as android.transition.ChangeBounds. A null value will cause transferred shared elements to blink to the final position. If no value is set, the default will be to use the same value as setSharedElementEnterTransition
.
@NonNull
public voidsetTargetFragment(@Nullable Fragment fragment, @NonNull int requestCode)
Optional target for this fragment. This may be used, for example, if this fragment is being started by another, and when done wants to give a result back to the first. The target set here is retained across instances via FragmentManager.putFragment()
.
Parameters | |
---|---|
@Nullable Fragment fragment |
The fragment that is the target of this one. |
@NonNull int requestCode |
Optional request code, for convenience if you are going to call back with |
@NonNull
public voidsetUserVisibleHint(@NonNull boolean isVisibleToUser)
Set a hint to the system about whether this fragment's UI is currently visible to the user. This hint defaults to true and is persistent across fragment instance state save and restore.
An app may set this to false to indicate that the fragment's UI is scrolled out of visibility or is otherwise not directly visible to the user. This may be used by the system to prioritize operations such as fragment lifecycle updates or loader ordering behavior.
Note: This method may be called outside of the fragment lifecycle. and thus has no ordering guarantees with regard to fragment lifecycle method calls.
Parameters | |
---|---|
@NonNull boolean isVisibleToUser |
true if this fragment's UI is currently visible to the user (default), false if it is not. |
@NonNull
public boolean shouldShowRequestPermissionRationale(@NonNull String permission)
Gets whether you should show UI with rationale before requesting a permission.
Returns | |
---|---|
boolean |
Whether you should show permission rationale UI. |
See also | |
---|---|
Context |
android.content.Context#checkSelfPermission(String) |
requestPermissions |
#requestPermissions(String[], int) |
onRequestPermissionsResult |
#onRequestPermissionsResult(int, String[], int[]) |
@NonNull
public void startActivity(@NonNull Intent intent)
Call Activity#startActivity(Intent) from the fragment's containing Activity.
@NonNull
public void startActivity(@NonNull Intent intent, @Nullable Bundle options)
Call Activity#startActivity(Intent, Bundle) from the fragment's containing Activity.
@NonNull
public voidstartActivityForResult(@NonNull Intent intent, @NonNull int requestCode)
Call Activity#startActivityForResult(Intent, int) from the fragment's containing Activity.
Parameters | |
---|---|
@NonNull Intent intent |
The intent to start. |
@NonNull int requestCode |
The request code to be returned in |
@NonNull
public voidstartActivityForResult(
@NonNull Intent intent,
@NonNull int requestCode,
@Nullable Bundle options
)
Call Activity#startActivityForResult(Intent, int, Bundle) from the fragment's containing Activity.
Parameters | |
---|---|
@NonNull Intent intent |
The intent to start. |
@NonNull int requestCode |
The request code to be returned in |
@Nullable Bundle options |
Additional options for how the Activity should be started. See Context#startActivity(Intent, Bundle) for more details. This value may be null. |
@NonNull
public voidstartIntentSenderForResult(
@NonNull IntentSender intent,
@NonNull int requestCode,
@Nullable Intent fillInIntent,
@NonNull int flagsMask,
@NonNull int flagsValues,
@NonNull int extraFlags,
@Nullable Bundle options
)
Call Activity#startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle) from the fragment's containing Activity.
Parameters | |
---|---|
@NonNull IntentSender intent |
The IntentSender to launch. |
@NonNull int requestCode |
The request code to be returned in |
@Nullable Intent fillInIntent |
If non-null, this will be provided as the intent parameter to IntentSender#sendIntent(Context, int, Intent, IntentSender.OnFinished, Handler). This value may be null. |
@NonNull int flagsMask |
Intent flags in the original IntentSender that you would like to change. |
@NonNull int flagsValues |
Desired values for any bits set in |
@NonNull int extraFlags |
Always set to 0. |
@Nullable Bundle options |
Additional options for how the Activity should be started. See Context#startActivity(Intent, Bundle) for more details. This value may be null. |
@NonNull
public void startPostponedEnterTransition()
Begin postponed transitions after postponeEnterTransition
was called. If postponeEnterTransition() was called, you must call startPostponedEnterTransition() or FragmentManager#executePendingTransactions()
to complete the FragmentTransaction. If postponement was interrupted with FragmentManager#executePendingTransactions()
, before {@code startPostponedEnterTransition()}
, animations may not run or may execute improperly.
See also | |
---|---|
Activity |
android.app.Activity#startPostponedEnterTransition() |
@NonNull
public void unregisterForContextMenu(@NonNull View view)
Prevents a context menu to be shown for the given view. This method will remove the OnCreateContextMenuListener on the view.
Parameters | |
---|---|
@NonNull View view |
The view that should stop showing a context menu. |
See also | |
---|---|
registerForContextMenu |
#registerForContextMenu(View) |