Fragment
open class Fragment : ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner, ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner
kotlin.Any | |
↳ | androidx.fragment.app.Fragment |
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:
- Your activity must extend
FragmentActivity
- You must call
FragmentActivity#getSupportFragmentManager
to get theFragmentManager
Summary
Nested classes |
|
---|---|
open |
Thrown by |
open |
State information that has been retrieved from a fragment instance through |
Public constructors |
|
---|---|
<init>() Constructor used by the default |
|
Alternate constructor that can be used to provide a default layout that will be inflated by |
Public methods |
|
---|---|
open Unit |
dump(@NonNull prefix: String, @Nullable fd: FileDescriptor?, @NonNull writer: PrintWriter, @Nullable args: Array<String!>?) Print the Fragments's state into the given stream. |
Boolean |
Subclasses can not override equals(). |
FragmentActivity? |
Return the |
open Boolean |
Returns whether the the exit transition and enter transition overlap or not. |
open Boolean |
Returns whether the the return transition and reenter transition overlap or not. |
Bundle? |
Return the arguments supplied when the fragment was instantiated, if any. |
FragmentManager |
Return a private FragmentManager for placing and managing Fragments inside of this Fragment. |
open Context? |
Return the |
open ViewModelProvider.Factory |
Returns the default |
open Any? |
Returns the Transition that will be used to move Views into the initial scene. |
open Any? |
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. |
FragmentManager? |
Return the FragmentManager for interacting with fragments associated with this fragment's activity. |
Any? |
getHost() Return the host object of this fragment. |
Int |
getId() Return the identifier this fragment is known by. |
LayoutInflater |
Returns the cached LayoutInflater used to inflate Views of this Fragment. |
open Lifecycle |
Returns the Lifecycle of the provider. |
open LoaderManager |
Return the LoaderManager for this fragment. |
Fragment? |
Returns the parent Fragment containing this Fragment. |
FragmentManager |
Return the FragmentManager for interacting with fragments associated with this fragment's activity. |
open Any? |
Returns the Transition that will be used to move Views in to the scene when returning due to popping a back stack. |
Resources |
Return |
Boolean | |
open Any? |
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. |
SavedStateRegistry | |
open Any? |
Returns the Transition that will be used for shared elements transferred into the content Scene. |
open Any? |
Return the Transition that will be used for shared elements transferred back during a pop of the back stack. |
String |
Return a localized string from the application's package's default string table. |
String |
Return a localized formatted string from the application's package's default string table, substituting the format arguments as defined in |
String? |
getTag() Get the tag name of the fragment, if specified. |
Fragment? |
Return the target fragment set by |
Int |
Return the target request code set by |
CharSequence |
Return a localized, styled CharSequence from the application's package's default string table. |
open Boolean | |
open View? |
getView() Get the root view for the fragment's layout (the one returned by |
open LifecycleOwner |
Get a |
open LiveData<LifecycleOwner!> |
Retrieve a |
open ViewModelStore |
Returns the |
Int |
hashCode() Subclasses can not override hashCode(). |
open static Fragment |
instantiate(@NonNull context: Context, @NonNull fname: String) Like |
open static Fragment |
instantiate(@NonNull context: Context, @NonNull fname: String, @Nullable args: Bundle?) Create a new instance of a Fragment with the given class name. |
Boolean |
isAdded() Return true if the fragment is currently added to its activity. |
Boolean |
Return true if the fragment has been explicitly detached from the UI. |
Boolean |
isHidden() Return true if the fragment has been hidden. |
Boolean |
Return true if the layout is included as part of an activity view hierarchy via the <fragment> tag. |
Boolean |
Return true if this fragment is currently being removed from its activity. |
Boolean |
Return true if the fragment is in the resumed state. |
Boolean |
Returns true if this fragment is added and its state has already been saved by its host. |
Boolean |
Return true if the fragment is currently visible to the user. |
open Unit |
onActivityCreated(@Nullable savedInstanceState: Bundle?) Called when the fragment's activity has been created and this fragment's view hierarchy instantiated. |
open Unit |
onActivityResult(requestCode: Int, resultCode: Int, @Nullable data: Intent?) Receive the result from a previous call to |
open Unit |
Called when a fragment is first attached to its context. |
open Unit |
Called when a fragment is first attached to its activity. |
open Unit |
onAttachFragment(@NonNull childFragment: Fragment) Called when a fragment is attached as a child of this fragment. |
open Unit |
onConfigurationChanged(@NonNull newConfig: Configuration) |
open Boolean |
onContextItemSelected(@NonNull item: MenuItem) This hook is called whenever an item in a context menu is selected. |
open Unit |
Called to do initial creation of a fragment. |
open Animation? |
onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int) Called when a fragment loads an animation. |
open Animator? |
onCreateAnimator(transit: Int, enter: Boolean, nextAnim: Int) Called when a fragment loads an animator. |
open Unit |
onCreateContextMenu(@NonNull : ContextMenu, @NonNull v: View, @Nullable : ContextMenuInfo?) Called when a context menu for the |
open Unit |
onCreateOptionsMenu(@NonNull : Menu, @NonNull inflater: MenuInflater) Initialize the contents of the Fragment host's standard options menu. |
open View? |
onCreateView(@NonNull inflater: LayoutInflater, @Nullable container: ViewGroup?, @Nullable savedInstanceState: Bundle?) Called to have the fragment instantiate its user interface view. |
open Unit |
Called when the fragment is no longer in use. |
open Unit |
Called when this fragment's option menu items are no longer being included in the overall options menu. |
open Unit |
Called when the view previously created by |
open Unit |
onDetach() Called when the fragment is no longer attached to its activity. |
open LayoutInflater |
onGetLayoutInflater(@Nullable savedInstanceState: Bundle?) Returns the LayoutInflater used to inflate Views of this Fragment. |
open Unit |
Called when the hidden state (as returned by |
open Unit |
onInflate(@NonNull context: Context, @NonNull attrs: AttributeSet, @Nullable savedInstanceState: Bundle?) Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity. |
open Unit |
onInflate(@NonNull activity: Activity, @NonNull attrs: AttributeSet, @Nullable savedInstanceState: Bundle?) Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity. |
open Unit | |
open Unit |
onMultiWindowModeChanged(isInMultiWindowMode: Boolean) Called when the Fragment's activity changes from fullscreen mode to multi-window mode and visa-versa. |
open Boolean |
onOptionsItemSelected(@NonNull item: MenuItem) This hook is called whenever an item in your options menu is selected. |
open Unit |
onOptionsMenuClosed(@NonNull : 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). |
open Unit |
onPause() Called when the Fragment is no longer resumed. |
open Unit |
onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean) Called by the system when the activity changes to and from picture-in-picture mode. |
open Unit |
onPrepareOptionsMenu(@NonNull : Menu) Prepare the Fragment host's standard options menu to be displayed. |
open Unit |
Callback for when the primary navigation state of this Fragment has changed. |
open Unit |
onRequestPermissionsResult(requestCode: Int, @NonNull permissions: Array<String!>, @NonNull grantResults: IntArray) Callback for the result from requesting permissions. |
open Unit |
onResume() Called when the fragment is visible to the user and actively running. |
open Unit |
onSaveInstanceState(@NonNull outState: Bundle) Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance of its process is restarted. |
open Unit |
onStart() Called when the Fragment is visible to the user. |
open Unit |
onStop() Called when the Fragment is no longer started. |
open Unit |
onViewCreated(@NonNull view: View, @Nullable savedInstanceState: Bundle?) Called immediately after |
open Unit |
onViewStateRestored(@Nullable savedInstanceState: Bundle?) Called when all saved state has been restored into the view hierarchy of the fragment. |
open Unit |
Postpone the entering Fragment transition until |
Unit |
postponeEnterTransition(duration: Long, @NonNull timeUnit: TimeUnit) Postpone the entering Fragment transition for a given amount of time and then call |
open Unit |
registerForContextMenu(@NonNull view: View) Registers a context menu to be shown for the given view (multiple views can show the context menu). |
Unit |
requestPermissions(@NonNull permissions: Array<String!>, requestCode: Int) Requests permissions to be granted to this application. |
FragmentActivity |
Return the |
Bundle |
Return the arguments supplied when the fragment was instantiated. |
Context |
Return the |
FragmentManager |
Return the FragmentManager for interacting with fragments associated with this fragment's activity. |
Any |
Return the host object of this fragment. |
Fragment |
Returns the parent Fragment containing this Fragment. |
View |
Get the root view for the fragment's layout (the one returned by |
open Unit |
Sets whether the the exit transition and enter transition overlap or not. |
open Unit |
Sets whether the the return transition and reenter transition overlap or not. |
open Unit |
setArguments(@Nullable args: Bundle?) Supply the construction arguments for this fragment. |
open Unit |
setEnterSharedElementCallback(@Nullable : SharedElementCallback?) 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. |
open Unit |
setEnterTransition(@Nullable transition: Any?) Sets the Transition that will be used to move Views into the initial scene. |
open Unit |
setExitSharedElementCallback(@Nullable : SharedElementCallback?) 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. |
open Unit |
setExitTransition(@Nullable transition: Any?) 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. |
open Unit |
setHasOptionsMenu(hasMenu: Boolean) Report that this fragment would like to participate in populating the options menu by receiving a call to |
open Unit |
setInitialSavedState(@Nullable state: Fragment.SavedState?) Set the initial saved state that this Fragment should restore itself from when first being constructed, as returned by |
open Unit |
Set a hint for whether this fragment's menu should be visible. |
open Unit |
setReenterTransition(@Nullable transition: Any?) Sets the Transition that will be used to move Views in to the scene when returning due to popping a back stack. |
open Unit |
setRetainInstance(retain: Boolean) Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). |
open Unit |
setReturnTransition(@Nullable transition: Any?) 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. |
open Unit |
setSharedElementEnterTransition(@Nullable : Any?) Sets the Transition that will be used for shared elements transferred into the content Scene. |
open Unit |
setSharedElementReturnTransition(@Nullable : Any?) Sets the Transition that will be used for shared elements transferred back during a pop of the back stack. |
open Unit |
setTargetFragment(@Nullable fragment: Fragment?, requestCode: Int) Optional target for this fragment. |
open Unit |
setUserVisibleHint(isVisibleToUser: Boolean) Set a hint to the system about whether this fragment's UI is currently visible to the user. |
open Boolean |
shouldShowRequestPermissionRationale(@NonNull permission: String) Gets whether you should show UI with rationale for requesting a permission. |
open Unit |
startActivity(intent: Intent!) Call |
open Unit |
startActivity(intent: Intent!, @Nullable options: Bundle?) Call |
open Unit |
startActivityForResult(intent: Intent!, requestCode: Int) Call |
open Unit |
startActivityForResult(intent: Intent!, requestCode: Int, @Nullable options: Bundle?) Call |
open Unit |
startIntentSenderForResult(intent: IntentSender!, requestCode: Int, @Nullable fillInIntent: Intent?, flagsMask: Int, flagsValues: Int, extraFlags: Int, @Nullable options: Bundle?) Call |
open Unit |
Begin postponed transitions after |
open String |
toString() |
open Unit |
unregisterForContextMenu(@NonNull view: View) Prevents a context menu to be shown for the given view. |
Extension functions |
||||||
---|---|---|---|---|---|---|
From androidx.fragment.app
|
||||||
From androidx.navigation.fragment
|
||||||
From androidx.navigation
|
Public constructors
<init>
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(Context)
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.
<init>
Fragment(@LayoutRes contentLayoutId: Int)
Alternate constructor that can be used to provide a default layout that will be inflated by onCreateView(LayoutInflater, ViewGroup, Bundle)
.
Public methods
dump
open fun dump(@NonNull prefix: String, @Nullable fd: FileDescriptor?, @NonNull writer: PrintWriter, @Nullable args: Array<String!>?): Unit
Print the Fragments's state into the given stream.
Parameters | |
---|---|
prefix |
String: Text to print at the front of each line. |
fd |
String: The raw file descriptor that the dump is being sent to. |
writer |
String: The PrintWriter to which you should dump your state. This will be closed for you after you return. |
args |
String: additional arguments to the dump request. |
getActivity
@Nullable fun getActivity(): FragmentActivity?
Return the FragmentActivity
this fragment is currently associated with. May return null
if the fragment is associated with a Context
instead.
See Also
getAllowEnterTransitionOverlap
open fun getAllowEnterTransitionOverlap(): Boolean
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.
Return | |
---|---|
Boolean: true when the enter transition should start as soon as possible or false to when it should wait until the exiting transition completes. |
getAllowReturnTransitionOverlap
open fun getAllowReturnTransitionOverlap(): Boolean
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.
Return | |
---|---|
Boolean: true to start the reenter transition when possible or false to wait until the return transition completes. |
getArguments
@Nullable fun getArguments(): Bundle?
Return the arguments supplied when the fragment was instantiated, if any.
getChildFragmentManager
@NonNull fun getChildFragmentManager(): FragmentManager
Return a private FragmentManager for placing and managing Fragments inside of this Fragment.
getContext
@Nullable open fun getContext(): Context?
Return the Context
this fragment is currently associated with.
See Also
getDefaultViewModelProviderFactory
@NonNull open fun getDefaultViewModelProviderFactory(): ViewModelProvider.Factory
Returns the default ViewModelProvider.Factory
that should be used when no custom Factory
is provided to the ViewModelProvider
constructors.
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.
Return | |
---|---|
ViewModelProvider.Factory: a ViewModelProvider.Factory |
getEnterTransition
@Nullable open fun getEnterTransition(): Any?
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
.
Return | |
---|---|
Any?: the Transition to use to move Views into the initial Scene. |
getExitTransition
@Nullable open fun getExitTransition(): Any?
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.
Return | |
---|---|
Any?: the Transition to use to move Views out of the Scene when the Fragment is being closed not due to popping the back stack. |
getFragmentManager
@Nullable fungetFragmentManager(): FragmentManager?
Deprecated: This has been removed in favor of getParentFragmentManager()
which throws an IllegalStateException
if the FragmentManager is null. Check if isAdded()
returns false
to determine if the FragmentManager is null
.
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
getHost
@Nullable fun getHost(): Any?
Return the host object of this fragment. May return null
if the fragment isn't currently being hosted.
See Also
getId
fun getId(): Int
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.
getLayoutInflater
@NonNull fun getLayoutInflater(): LayoutInflater
Returns the cached LayoutInflater used to inflate Views of this Fragment. If onGetLayoutInflater(Bundle)
has not been called onGetLayoutInflater(Bundle)
will be called with a null
argument and that value will be cached.
The cached LayoutInflater will be replaced immediately prior to onCreateView(LayoutInflater, ViewGroup, Bundle)
and cleared immediately after onDetach()
.
Return | |
---|---|
LayoutInflater: The LayoutInflater used to inflate Views of this Fragment. |
getLifecycle
@NonNull open fun getLifecycle(): Lifecycle
Returns the Lifecycle of the provider.
Overriding this method is no longer supported and this method will be made final
in a future version of Fragment.
Return | |
---|---|
Lifecycle: The lifecycle of the provider. |
getLoaderManager
@NonNull open fungetLoaderManager(): LoaderManager
Deprecated: Use LoaderManager.getInstance(this)
.
Return the LoaderManager for this fragment.
getParentFragment
@Nullable fun getParentFragment(): Fragment?
Returns the parent Fragment containing this Fragment. If this Fragment is attached directly to an Activity, returns null.
getParentFragmentManager
@NonNull fun getParentFragmentManager(): FragmentManager
Return the FragmentManager for interacting with fragments associated with this fragment's activity. Note that this will 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()
.
Exceptions | |
---|---|
IllegalStateException |
if not associated with a transaction or host. |
getReenterTransition
@Nullable open fun getReenterTransition(): Any?
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()
.
Return | |
---|---|
Any?: the Transition to use to move Views into the scene when reentering from a previously-started Activity due to popping the back stack. |
getRetainInstance
fun getRetainInstance(): Boolean
getReturnTransition
@Nullable open fun getReturnTransition(): Any?
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()
.
Return | |
---|---|
Any?: the Transition to use to move Views out of the Scene when the Fragment is preparing to close due to popping the back stack. |
getSavedStateRegistry
@NonNull fun getSavedStateRegistry(): SavedStateRegistry
getSharedElementEnterTransition
@Nullable open fun getSharedElementEnterTransition(): Any?
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.
Return | |
---|---|
Any?: The Transition to use for shared elements transferred into the content Scene. |
getSharedElementReturnTransition
@Nullable open fun getSharedElementReturnTransition(): Any?
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(Object)
.
Return | |
---|---|
Any?: The Transition to use for shared elements transferred out of the content Scene. |
getString
@NonNull fun getString(@StringRes resId: Int): String
Return a localized string from the application's package's default string table.
Parameters | |
---|---|
resId |
Int: Resource id for the string |
getString
@NonNull fun getString(@StringRes resId: Int, @Nullable vararg formatArgs: Any!): String
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 java.lang.String#format
.
Parameters | |
---|---|
resId |
Int: Resource id for the format string |
formatArgs |
Int: The format arguments that will be used for substitution. |
getTargetFragment
@Nullable fun getTargetFragment(): Fragment?
Return the target fragment set by setTargetFragment
.
getTargetRequestCode
fun getTargetRequestCode(): Int
Return the target request code set by setTargetFragment
.
getText
@NonNull fun getText(@StringRes resId: Int): CharSequence
Return a localized, styled CharSequence from the application's package's default string table.
Parameters | |
---|---|
resId |
Int: Resource id for the CharSequence text |
getUserVisibleHint
open fungetUserVisibleHint(): Boolean
Deprecated: Use FragmentTransaction#setMaxLifecycle(Fragment, Lifecycle.State)
instead.
Return | |
---|---|
Boolean: The current value of the user-visible hint on this fragment. |
See Also
getView
@Nullable open fun getView(): View?
Get the root view for the fragment's layout (the one returned by onCreateView
), if provided.
Return | |
---|---|
View?: The fragment's root view, or null if it has no layout. |
getViewLifecycleOwner
@MainThread @NonNull open fun getViewLifecycleOwner(): LifecycleOwner
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:
created
afteronViewStateRestored(Bundle)
started
afteronStart()
resumed
afteronResume()
paused
beforeonPause()
stopped
beforeonStop()
destroyed
beforeonDestroyView()
onCreateView(LayoutInflater, ViewGroup, Bundle)
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.
Return | |
---|---|
LifecycleOwner: A LifecycleOwner that represents the Fragment's View lifecycle. |
Exceptions | |
---|---|
IllegalStateException |
if the Fragment's View is null . |
getViewLifecycleOwnerLiveData
@NonNull open fun getViewLifecycleOwnerLiveData(): LiveData<LifecycleOwner!>
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.
Return | |
---|---|
LiveData<LifecycleOwner!>: A LiveData that changes in sync with getViewLifecycleOwner() . |
getViewModelStore
@NonNull open fun getViewModelStore(): ViewModelStore
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.
Return | |
---|---|
ViewModelStore: a ViewModelStore |
Exceptions | |
---|---|
IllegalStateException |
if called before the Fragment is attached i.e., before onAttach(). |
instantiate
@NonNull open static funinstantiate(@NonNull context: Context, @NonNull fname: String): Fragment
Deprecated: Use FragmentManager#getFragmentFactory()
and FragmentFactory#instantiate(ClassLoader, String)
Like instantiate(Context, String, Bundle)
but with a null argument Bundle.
instantiate
@NonNull open static funinstantiate(@NonNull context: Context, @NonNull fname: String, @Nullable args: Bundle?): Fragment
Deprecated: Use FragmentManager#getFragmentFactory()
and FragmentFactory#instantiate(ClassLoader, String)
, manually calling setArguments(Bundle)
on the returned Fragment.
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(Bundle)
.
Parameters | |
---|---|
context |
Context: The calling context being used to instantiate the fragment. This is currently just used to get its ClassLoader. |
fname |
Context: The class name of the fragment to instantiate. |
args |
Context: Bundle of arguments to supply to the fragment, which it can retrieve with getArguments() . May be null. |
Return | |
---|---|
Fragment: Returns a new fragment instance. |
Exceptions | |
---|---|
InstantiationException |
If there is a failure in instantiating the given fragment class. This is a runtime exception; it is not normally expected to happen. |
isDetached
fun isDetached(): Boolean
Return true if the fragment has been explicitly detached from the UI. That is, FragmentTransaction.detach(Fragment)
has been used on it.
isHidden
fun isHidden(): Boolean
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.
isInLayout
fun isInLayout(): Boolean
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, except in the case where an old fragment is restored from a previous state and it does not appear in the layout of the current state.
isRemoving
fun isRemoving(): Boolean
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.
isResumed
fun isResumed(): Boolean
Return true if the fragment is in the resumed state. This is true for the duration of onResume()
and onPause()
as well.
isStateSaved
fun isStateSaved(): Boolean
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(Bundle)
will fail.
Return | |
---|---|
Boolean: true if this fragment's state has already been saved by its host |
isVisible
fun isVisible(): Boolean
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.
onActivityCreated
@MainThread @CallSuper open fun onActivityCreated(@Nullable savedInstanceState: Bundle?): Unit
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(boolean)
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(Bundle)
.
Parameters | |
---|---|
savedInstanceState |
Bundle?: If the fragment is being re-created from a previous saved state, this is the state. |
onActivityResult
open fun onActivityResult(requestCode: Int, resultCode: Int, @Nullable data: Intent?): Unit
Receive the result from a previous call to startActivityForResult(Intent, int)
. This follows the related Activity API as described there in Activity#onActivityResult(int, int, Intent)
.
Parameters | |
---|---|
requestCode |
Int: The integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from. |
resultCode |
Int: The integer result code returned by the child activity through its setResult(). |
data |
Int: An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). |
onAttach
@MainThread @CallSuper open fun onAttach(@NonNull context: Context): Unit
Called when a fragment is first attached to its context. onCreate(Bundle)
will be called after this.
onAttach
@MainThread @CallSuper open funonAttach(@NonNull activity: Activity): Unit
Deprecated: See onAttach(Context)
.
Called when a fragment is first attached to its activity. onCreate(Bundle)
will be called after this.
onAttachFragment
@MainThread open fun onAttachFragment(@NonNull childFragment: Fragment): Unit
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
.
Parameters | |
---|---|
childFragment |
Fragment: child fragment being attached |
onConfigurationChanged
@CallSuper open fun onConfigurationChanged(@NonNull newConfig: Configuration): Unit
onContextItemSelected
@MainThread open fun onContextItemSelected(@NonNull item: MenuItem): Boolean
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 | |
---|---|
item |
MenuItem: The context menu item that was selected. |
Return | |
---|---|
Boolean: boolean Return false to allow normal context menu processing to proceed, true to consume it here. |
onCreate
@MainThread @CallSuper open fun onCreate(@Nullable savedInstanceState: Bundle?): Unit
Called to do initial creation of a fragment. This is called after onAttach(Activity)
and before onCreateView(LayoutInflater, ViewGroup, Bundle)
.
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, see onActivityCreated(Bundle)
.
Any restored child fragments will be created before the base Fragment.onCreate
method returns.
Parameters | |
---|---|
savedInstanceState |
Bundle?: If the fragment is being re-created from a previous saved state, this is the state. |
onCreateAnimation
@MainThread @Nullable open fun onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int): Animation?
Called when a fragment loads an animation. Note that if FragmentTransaction#setCustomAnimations(int, int)
was called with Animator
resources instead of Animation
resources, nextAnim
will be an animator resource.
Parameters | |
---|---|
transit |
Int: The value set in FragmentTransaction#setTransition(int) or 0 if not set. |
enter |
Int: true when the fragment is added/attached/shown or false when the fragment is removed/detached/hidden. |
nextAnim |
Int: The resource set in FragmentTransaction#setCustomAnimations(int, int) , FragmentTransaction#setCustomAnimations(int, int, int, int) , or 0 if neither was called. The value will depend on the current operation. |
onCreateAnimator
@MainThread @Nullable open fun onCreateAnimator(transit: Int, enter: Boolean, nextAnim: Int): Animator?
Called when a fragment loads an animator. This will be called when onCreateAnimation(int, boolean, int)
returns null. Note that if FragmentTransaction#setCustomAnimations(int, int)
was called with Animation
resources instead of Animator
resources, nextAnim
will be an animation resource.
Parameters | |
---|---|
transit |
Int: The value set in FragmentTransaction#setTransition(int) or 0 if not set. |
enter |
Int: true when the fragment is added/attached/shown or false when the fragment is removed/detached/hidden. |
nextAnim |
Int: The resource set in FragmentTransaction#setCustomAnimations(int, int) , FragmentTransaction#setCustomAnimations(int, int, int, int) , or 0 if neither was called. The value will depend on the current operation. |
onCreateContextMenu
@MainThread open fun onCreateContextMenu(@NonNull : ContextMenu, @NonNull v: View, @Nullable : ContextMenuInfo?): Unit
Called when a context menu for the 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 menuInfo
)).
Use onContextItemSelected(android.view.MenuItem)
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.
onCreateOptionsMenu
@MainThread open fun onCreateOptionsMenu(@NonNull : Menu, @NonNull inflater: MenuInflater): Unit
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 | |
---|---|
menu |
Menu: The options menu in which you place your items. |
onCreateView
@MainThread @Nullable open fun onCreateView(@NonNull inflater: LayoutInflater, @Nullable container: ViewGroup?, @Nullable savedInstanceState: Bundle?): View?
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(Bundle)
and onActivityCreated(Bundle)
.
A default View can be returned by calling Fragment(int)
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(View, Bundle)
.
If you return a View from here, you will later be called in onDestroyView
when the view is being released.
Parameters | |
---|---|
inflater |
LayoutInflater: The LayoutInflater object that can be used to inflate any views in the fragment, |
container |
LayoutInflater: 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. |
savedInstanceState |
LayoutInflater: If non-null, this fragment is being re-constructed from a previous saved state as given here. |
Return | |
---|---|
View?: Return the View for the fragment's UI, or null. |
onDestroy
@MainThread @CallSuper open fun onDestroy(): Unit
Called when the fragment is no longer in use. This is called after onStop()
and before onDetach()
.
onDestroyOptionsMenu
@MainThread open fun onDestroyOptionsMenu(): Unit
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(Menu, MenuInflater)
was not called).
onDestroyView
@MainThread @CallSuper open fun onDestroyView(): Unit
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.
onDetach
@MainThread @CallSuper open fun onDetach(): Unit
Called when the fragment is no longer attached to its activity. This is called after onDestroy()
.
onGetLayoutInflater
@NonNull open fun onGetLayoutInflater(@Nullable savedInstanceState: Bundle?): LayoutInflater
Returns the LayoutInflater used to inflate Views of this Fragment. The default implementation will throw an exception if the Fragment is not attached.
Parameters | |
---|---|
savedInstanceState |
Bundle?: If the fragment is being re-created from a previous saved state, this is the state. |
Return | |
---|---|
LayoutInflater: The LayoutInflater used to inflate Views of this Fragment. |
onHiddenChanged
@MainThread open fun onHiddenChanged(: Boolean): Unit
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 | |
---|---|
hidden |
Boolean: True if the fragment is now hidden, false otherwise. |
onInflate
@UiThread @CallSuper open fun onInflate(@NonNull context: Context, @NonNull attrs: AttributeSet, @Nullable savedInstanceState: Bundle?): Unit
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 before the fragment's onAttach(Context)
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()
:
Note that parsing the XML attributes uses a "styleable" resource. The declaration for the styleable used here is:
The fragment can then be declared within its activity's content layout through a tag like this:
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:
Parameters | |
---|---|
context |
Context: The Activity that is inflating this fragment. |
attrs |
Context: The attributes at the tag where the fragment is being created. |
savedInstanceState |
Context: If the fragment is being re-created from a previous saved state, this is the state. |
onInflate
@UiThread @CallSuper open funonInflate(@NonNull activity: Activity, @NonNull attrs: AttributeSet, @Nullable savedInstanceState: Bundle?): Unit
Deprecated: See onInflate(Context, AttributeSet, Bundle)
.
Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity.
onLowMemory
@MainThread @CallSuper open fun onLowMemory(): Unit
onMultiWindowModeChanged
open fun onMultiWindowModeChanged(isInMultiWindowMode: Boolean): Unit
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 | |
---|---|
isInMultiWindowMode |
Boolean: True if the activity is in multi-window mode. |
onOptionsItemSelected
@MainThread open fun onOptionsItemSelected(@NonNull item: MenuItem): Boolean
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 | |
---|---|
item |
MenuItem: The menu item that was selected. |
Return | |
---|---|
Boolean: boolean Return false to allow normal menu processing to proceed, true to consume it here. |
See Also
onOptionsMenuClosed
@MainThread open fun onOptionsMenuClosed(@NonNull : Menu): Unit
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 | |
---|---|
menu |
Menu: The options menu as last shown or first initialized by onCreateOptionsMenu(). |
onPause
@MainThread @CallSuper open fun onPause(): Unit
Called when the Fragment is no longer resumed. This is generally tied to Activity.onPause
of the containing Activity's lifecycle.
onPictureInPictureModeChanged
open fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean): Unit
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 | |
---|---|
isInPictureInPictureMode |
Boolean: True if the activity is in picture-in-picture mode. |
onPrepareOptionsMenu
@MainThread open fun onPrepareOptionsMenu(@NonNull : Menu): Unit
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 | |
---|---|
menu |
Menu: The options menu as last shown or first initialized by onCreateOptionsMenu(). |
onPrimaryNavigationFragmentChanged
@MainThread open fun onPrimaryNavigationFragmentChanged(: Boolean): Unit
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 androidx.fragment.app.FragmentTransaction#setPrimaryNavigationFragment
or due to the primary navigation fragment changing in a parent FragmentManager.
Parameters | |
---|---|
isPrimaryNavigationFragment |
Boolean: True if and only if this Fragment and any parent fragment is set as the primary navigation fragment via androidx.fragment.app.FragmentTransaction#setPrimaryNavigationFragment . |
onRequestPermissionsResult
open fun onRequestPermissionsResult(requestCode: Int, @NonNull permissions: Array<String!>, @NonNull grantResults: IntArray): Unit
Callback for the result from requesting permissions. This method is invoked for every call on requestPermissions(String[], int)
.
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 | |
---|---|
requestCode |
Int: The request code passed in requestPermissions(String[], int) . |
permissions |
Int: The requested permissions. Never null. |
grantResults |
Int: The grant results for the corresponding permissions which is either android.content.pm.PackageManager#PERMISSION_GRANTED or android.content.pm.PackageManager#PERMISSION_DENIED . Never null. |
See Also
onResume
@MainThread @CallSuper open fun onResume(): Unit
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.
onSaveInstanceState
@MainThread open fun onSaveInstanceState(@NonNull outState: Bundle): Unit
Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance of 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(Bundle)
, onCreateView(LayoutInflater, ViewGroup, Bundle)
, and onActivityCreated(Bundle)
.
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 | |
---|---|
outState |
Bundle: Bundle in which to place your saved state. |
onStart
@MainThread @CallSuper open fun onStart(): Unit
Called when the Fragment is visible to the user. This is generally tied to Activity.onStart
of the containing Activity's lifecycle.
onStop
@MainThread @CallSuper open fun onStop(): Unit
Called when the Fragment is no longer started. This is generally tied to Activity.onStop
of the containing Activity's lifecycle.
onViewCreated
@MainThread open fun onViewCreated(@NonNull view: View, @Nullable savedInstanceState: Bundle?): Unit
Called immediately after onCreateView(LayoutInflater, ViewGroup, Bundle)
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 | |
---|---|
view |
View: The View returned by onCreateView(LayoutInflater, ViewGroup, Bundle) . |
savedInstanceState |
View: If non-null, this fragment is being re-constructed from a previous saved state as given here. |
onViewStateRestored
@MainThread @CallSuper open fun onViewStateRestored(@Nullable savedInstanceState: Bundle?): Unit
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 onActivityCreated(Bundle)
and before onStart()
.
Parameters | |
---|---|
savedInstanceState |
Bundle?: If the fragment is being re-created from a previous saved state, this is the state. |
postponeEnterTransition
open fun postponeEnterTransition(): Unit
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(Bundle)
, onAttach(Context)
, or onCreateView(LayoutInflater, ViewGroup, Bundle)
}. 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.
postponeEnterTransition
fun postponeEnterTransition(duration: Long, @NonNull timeUnit: TimeUnit): Unit
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(Bundle)
, onAttach(Context)
, or onCreateView(LayoutInflater, ViewGroup, Bundle)
}.
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.
Parameters | |
---|---|
duration |
Long: The length of the delay in timeUnit units |
timeUnit |
Long: The units of time for duration |
registerForContextMenu
open fun registerForContextMenu(@NonNull view: View): Unit
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(ContextMenu, View, ContextMenuInfo)
will be called when it is time to show the context menu.
Parameters | |
---|---|
view |
View: The view that should show a context menu. |
See Also
requestPermissions
fun requestPermissions(@NonNull permissions: Array<String!>, requestCode: Int): Unit
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 android.content.pm.PermissionInfo#PROTECTION_NORMAL
are granted at install time if requested in the manifest. Signature permissions android.content.pm.PermissionInfo#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.
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.
A sample permissions request looks like this:
<code><p> private void showContacts() { if (getActivity().checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS); } else { doShowContacts(); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS && grantResults[0] == PackageManager.PERMISSION_GRANTED) { doShowContacts(); } } </p></code>
Parameters | |
---|---|
permissions |
Array<String!>: The requested permissions. |
requestCode |
Array<String!>: Application specific request code to match with a result reported to onRequestPermissionsResult(int, String[], int[]) . |
requireActivity
@NonNull fun requireActivity(): FragmentActivity
Return the FragmentActivity
this fragment is currently associated with.
Exceptions | |
---|---|
IllegalStateException |
if not currently associated with an activity or if associated only with a context. |
See Also
requireArguments
@NonNull fun requireArguments(): Bundle
Return the arguments supplied when the fragment was instantiated.
Exceptions | |
---|---|
IllegalStateException |
if no arguments were supplied to the Fragment. |
See Also
requireContext
@NonNull fun requireContext(): Context
Return the Context
this fragment is currently associated with.
Exceptions | |
---|---|
IllegalStateException |
if not currently associated with a context. |
See Also
requireFragmentManager
@NonNull funrequireFragmentManager(): FragmentManager
Deprecated: This has been renamed to getParentFragmentManager()
to make it clear that you are accessing the FragmentManager that contains this Fragment and not the FragmentManager associated with child Fragments.
Return the FragmentManager for interacting with fragments associated with this fragment's activity. Note that this will 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()
.
Exceptions | |
---|---|
IllegalStateException |
if not associated with a transaction or host. |
See Also
requireHost
@NonNull fun requireHost(): Any
Return the host object of this fragment.
Exceptions | |
---|---|
IllegalStateException |
if not currently associated with a host. |
See Also
requireParentFragment
@NonNull fun requireParentFragment(): Fragment
Returns the parent Fragment containing this Fragment.
Exceptions | |
---|---|
IllegalStateException |
if this Fragment is attached directly to an Activity or other Fragment host. |
See Also
requireView
@NonNull fun requireView(): View
Get the root view for the fragment's layout (the one returned by onCreateView
).
Exceptions | |
---|---|
IllegalStateException |
if no view was returned by onCreateView . |
See Also
setAllowEnterTransitionOverlap
open fun setAllowEnterTransitionOverlap(allow: Boolean): Unit
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 | |
---|---|
allow |
Boolean: true to start the enter transition when possible or false to wait until the exiting transition completes. |
setAllowReturnTransitionOverlap
open fun setAllowReturnTransitionOverlap(allow: Boolean): Unit
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 | |
---|---|
allow |
Boolean: true to start the reenter transition when possible or false to wait until the return transition completes. |
setArguments
open fun setArguments(@Nullable args: Bundle?): Unit
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.
setEnterSharedElementCallback
open fun setEnterSharedElementCallback(@Nullable : SharedElementCallback?): Unit
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 | |
---|---|
callback |
SharedElementCallback?: Used to manipulate the shared element transitions on this Fragment when added not as a pop from the back stack. |
setEnterTransition
open fun setEnterTransition(@Nullable transition: Any?): Unit
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.
Parameters | |
---|---|
transition |
Any?: The Transition to use to move Views into the initial Scene. transition must be an android.transition.Transition or androidx.transition.Transition . |
setExitSharedElementCallback
open fun setExitSharedElementCallback(@Nullable : SharedElementCallback?): Unit
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 | |
---|---|
callback |
SharedElementCallback?: Used to manipulate the shared element transitions on this Fragment when added as a pop from the back stack. |
setExitTransition
open fun setExitTransition(@Nullable transition: Any?): Unit
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.
Parameters | |
---|---|
transition |
Any?: The Transition to use to move Views out of the Scene when the Fragment is being closed not due to popping the back stack. transition must be an android.transition.Transition or androidx.transition.Transition . |
setHasOptionsMenu
open fun setHasOptionsMenu(hasMenu: Boolean): Unit
Report that this fragment would like to participate in populating the options menu by receiving a call to onCreateOptionsMenu
and related methods.
Parameters | |
---|---|
hasMenu |
Boolean: If true, the fragment has menu items to contribute. |
setInitialSavedState
open fun setInitialSavedState(@Nullable state: Fragment.SavedState?): Unit
Set the initial saved state that this Fragment should restore itself from when first being constructed, as returned by FragmentManager.saveFragmentInstanceState
.
Parameters | |
---|---|
state |
Fragment.SavedState?: The state the fragment should be restored from. |
setMenuVisibility
open fun setMenuVisibility(: Boolean): Unit
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 | |
---|---|
menuVisible |
Boolean: The default is true, meaning the fragment's menu will be shown as usual. If false, the user will not see the menu. |
setReenterTransition
open fun setReenterTransition(@Nullable transition: Any?): Unit
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()
.
Parameters | |
---|---|
transition |
Any?: The Transition to use to move Views into the scene when reentering from a previously-started Activity due to popping the back stack. transition must be an android.transition.Transition or androidx.transition.Transition . |
setRetainInstance
open fun setRetainInstance(retain: Boolean): Unit
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 (butonDetach()
still will be, because the fragment is being detached from its current activity). -
onCreate(Bundle)
will not be called since the fragment is not being re-created. -
onAttach(Activity)
andonActivityCreated(Bundle)
will still be called.
setReturnTransition
open fun setReturnTransition(@Nullable transition: Any?): Unit
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(Object)
.
Parameters | |
---|---|
transition |
Any?: The Transition to use to move Views out of the Scene when the Fragment is preparing to close due to popping the back stack. transition must be an android.transition.Transition or androidx.transition.Transition . |
setSharedElementEnterTransition
open fun setSharedElementEnterTransition(@Nullable : Any?): Unit
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.
Parameters | |
---|---|
transition |
Any?: The Transition to use for shared elements transferred into the content Scene. transition must be an android.transition.Transition or androidx.transition.Transition . |
setSharedElementReturnTransition
open fun setSharedElementReturnTransition(@Nullable : Any?): Unit
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(Object)
.
Parameters | |
---|---|
transition |
Any?: The Transition to use for shared elements transferred out of the content Scene. transition must be an android.transition.Transition or androidx.transition.Transition . |
setTargetFragment
open fun setTargetFragment(@Nullable fragment: Fragment?, requestCode: Int): Unit
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 | |
---|---|
fragment |
Fragment?: The fragment that is the target of this one. |
requestCode |
Fragment?: Optional request code, for convenience if you are going to call back with onActivityResult(int, int, Intent) . |
setUserVisibleHint
open funsetUserVisibleHint(isVisibleToUser: Boolean): Unit
Deprecated: If you are manually calling this method, use FragmentTransaction#setMaxLifecycle(Fragment, Lifecycle.State)
instead. If overriding this method, behavior implemented when passing in true
should be moved to Fragment#onResume()
, and behavior implemented when passing in false
should be moved to Fragment#onPause()
.
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 | |
---|---|
isVisibleToUser |
Boolean: true if this fragment's UI is currently visible to the user (default), false if it is not. |
shouldShowRequestPermissionRationale
open fun shouldShowRequestPermissionRationale(@NonNull permission: String): Boolean
Gets whether you should show UI with rationale for requesting a permission. You should do this only if you do not have the permission and the context in which the permission is requested does not clearly communicate to the user what would be the benefit from granting this permission.
For example, if you write a camera app, requesting the camera permission would be expected by the user and no rationale for why it is requested is needed. If however, the app needs location for tagging photos then a non-tech savvy user may wonder how location is related to taking photos. In this case you may choose to show UI with rationale of requesting this permission.
Parameters | |
---|---|
permission |
String: A permission your app wants to request. |
Return | |
---|---|
Boolean: Whether you can show permission rationale UI. |
startActivity
open fun startActivity(intent: Intent!): Unit
Call Activity#startActivity(Intent)
from the fragment's containing Activity.
startActivity
open fun startActivity(intent: Intent!, @Nullable options: Bundle?): Unit
Call Activity#startActivity(Intent, Bundle)
from the fragment's containing Activity.
startActivityForResult
open fun startActivityForResult(intent: Intent!, requestCode: Int): Unit
Call Activity#startActivityForResult(Intent, int)
from the fragment's containing Activity.
startActivityForResult
open fun startActivityForResult(intent: Intent!, requestCode: Int, @Nullable options: Bundle?): Unit
Call Activity#startActivityForResult(Intent, int, Bundle)
from the fragment's containing Activity.
startIntentSenderForResult
open fun startIntentSenderForResult(intent: IntentSender!, requestCode: Int, @Nullable fillInIntent: Intent?, flagsMask: Int, flagsValues: Int, extraFlags: Int, @Nullable options: Bundle?): Unit
Call Activity#startIntentSenderForResult(IntentSender, int, Intent, int, int, int, * Bundle)
from the fragment's containing Activity.
startPostponedEnterTransition
open fun startPostponedEnterTransition(): Unit
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 startPostponedEnterTransition()
, animations may not run or may execute improperly.
toString
@NonNull open fun toString(): String
unregisterForContextMenu
open fun unregisterForContextMenu(@NonNull view: View): Unit
Prevents a context menu to be shown for the given view. This method will remove the OnCreateContextMenuListener
on the view.
Parameters | |
---|---|
view |
View: The view that should stop showing a context menu. |
See Also