Fragment
class Fragment : ComponentCallbacks, View.OnCreateContextMenuListener, LifecycleOwner, ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner, ActivityResultCaller, ContextAware
AbstractListDetailFragment |
A fragment supports adaptive two-pane layout. |
AbstractProgressFragment |
The base class for |
AmbientModeSupport |
This class is deprecated. Use |
BrandedSupportFragment |
Fragment class for managing search and branding using a view that implements |
ComposableFragment |
This class provides a |
DialogFragment |
A fragment that displays a dialog window, floating in the foreground of its activity's window. |
GuidedStepSupportFragment |
A GuidedStepSupportFragment is used to guide the user through a decision or series of decisions. |
HeadersSupportFragment |
An fragment containing a list of row headers. |
LeanbackPreferenceDialogFragmentCompat |
A fragment that shows |
LeanbackSettingsFragmentCompat |
This fragment provides a container for displaying a |
ListFragment |
Static library support version of the framework's |
MediaRouteDiscoveryFragment |
Media route discovery fragment. |
NavHostFragment |
NavHostFragment provides an area within your layout for self-contained navigation to occur. |
OnboardingSupportFragment |
An OnboardingSupportFragment provides a common and simple way to build onboarding screen for applications. |
PdfViewerFragment |
A Fragment that renders a PDF document. |
PlaybackSupportFragment |
A fragment for displaying playback controls and related content. |
PreferenceFragmentCompat |
A PreferenceFragmentCompat is the entry point to using the Preference library. |
PreferenceHeaderFragmentCompat |
|
RowsSupportFragment |
An ordered set of rows of leanback widgets. |
SearchSupportFragment |
A fragment to handle searches. |
AppCompatDialogFragment |
A special version of |
BaseLeanbackPreferenceFragmentCompat |
This fragment provides a preference fragment with leanback-style behavior, suitable for embedding into broader UI elements. |
BaseSupportFragment |
Base class for leanback Fragments. |
BrowseSupportFragment |
A fragment for creating Leanback browse screens. |
ComposableNavHostFragment |
A |
DefaultProgressFragment |
The default |
DetailsSupportFragment |
A fragment for creating Leanback details screens. |
DynamicNavHostFragment |
The |
EditTextPreferenceDialogFragmentCompat |
|
EditablePdfViewerFragment |
A |
ErrorSupportFragment |
A fragment for displaying an error indication. |
LeanbackEditTextPreferenceDialogFragmentCompat |
Implemented a dialog to input text. |
LeanbackListPreferenceDialogFragmentCompat |
Implemented a dialog to show |
LeanbackPreferenceFragmentCompat |
This fragment provides a fully decorated leanback-style preference fragment, including a list background and header. |
ListPreferenceDialogFragmentCompat |
|
MediaRouteChooserDialogFragment |
Media route chooser dialog fragment. |
MediaRouteControllerDialogFragment |
Media route controller dialog fragment. |
MultiSelectListPreferenceDialogFragmentCompat |
|
PreferenceDialogFragmentCompat |
Abstract base class which presents a dialog associated with a |
VerticalGridSupportFragment |
A fragment for creating leanback vertical grids. |
VideoSupportFragment |
Subclass of |
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
getSupportFragmentManagerto get theFragmentManager
Summary
Nested types |
|---|
|
Thrown by |
class Fragment.SavedState : ParcelableState information that has been retrieved from a fragment instance through |
Public constructors |
|---|
Fragment()Constructor used by the default |
@ContentViewAlternate constructor that can be called from your default, no argument constructor to provide a default layout that will be inflated by |
Public functions |
|
|---|---|
Unit |
Add a new |
Unit |
dump(Print the Fragments's state into the given stream. |
Boolean |
Subclasses can not override equals(). |
FragmentActivity? |
Return the |
Boolean |
Returns whether the the exit transition and enter transition overlap or not. |
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. |
Context? |
Return the |
CreationExtras |
Returns the default |
ViewModelProvider.Factory |
Returns the default |
Any? |
Returns the Transition that will be used to move Views into the initial scene. |
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? |
This function is deprecated. This has been removed in favor of |
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. |
Lifecycle |
Returns the Lifecycle of the provider. |
LoaderManager |
This function is deprecated. |
Fragment? |
Returns the parent Fragment containing this Fragment. |
FragmentManager |
Return the FragmentManager for interacting with fragments associated with this fragment's activity. |
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 |
This function is deprecated. Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment. |
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 |
The |
Any? |
Returns the Transition that will be used for shared elements transferred into the content Scene. |
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? |
This function is deprecated. Instead of using a target fragment to pass results, use |
Int |
This function is deprecated. When using the target fragment replacement of |
CharSequence |
Return a localized, styled CharSequence from the application's package's default string table. |
Boolean |
This function is deprecated. Use |
View? |
getView()Get the root view for the fragment's layout (the one returned by |
LifecycleOwner |
Get a |
LiveData<LifecycleOwner!> |
Retrieve a |
ViewModelStore |
Returns the |
Int |
hashCode()Subclasses can not override hashCode(). |
java-static Fragment |
This function is deprecated. Use |
java-static Fragment |
This function is deprecated. Use |
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 |
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. |
Unit |
@MainThreadThis function is deprecated. use |
Unit |
This function is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an |
Unit |
@MainThreadThis function is deprecated. See |
Unit |
@MainThreadCalled when a fragment is first attached to its context. |
Unit |
@MainThreadThis function is deprecated. The responsibility for listening for fragments being attached has been moved to FragmentManager. |
Unit |
@CallSuper |
Boolean |
This hook is called whenever an item in a context menu is selected. |
Unit |
@MainThreadCalled to do initial creation of a fragment. |
Animation? |
@MainThreadCalled when a fragment loads an animation. |
Animator? |
@MainThreadCalled when a fragment loads an animator. |
Unit |
@MainThreadCalled when a context menu for the |
Unit |
@MainThreadThis function is deprecated.
|
View? |
@MainThreadCalled to have the fragment instantiate its user interface view. |
Unit |
Called when the fragment is no longer in use. |
Unit |
This function is deprecated.
|
Unit |
Called when the view previously created by |
Unit |
Called when the fragment is no longer attached to its activity. |
LayoutInflater |
onGetLayoutInflater(savedInstanceState: Bundle?)Returns the LayoutInflater used to inflate Views of this Fragment. |
Unit |
@MainThreadCalled when the hidden state (as returned by |
Unit |
This function is deprecated. See |
Unit |
Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity. |
Unit |
This function is deprecated. |
Unit |
onMultiWindowModeChanged(isInMultiWindowMode: Boolean)Called when the Fragment's activity changes from fullscreen mode to multi-window mode and visa-versa. |
Boolean |
This function is deprecated.
|
Unit |
@MainThreadThis function is deprecated.
|
Unit |
Called when the Fragment is no longer resumed. |
Unit |
onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean)Called by the system when the activity changes to and from picture-in-picture mode. |
Unit |
@MainThreadThis function is deprecated.
|
Unit |
@MainThreadCallback for when the primary navigation state of this Fragment has changed. |
Unit |
This function is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an |
Unit |
Called when the fragment is visible to the user and actively running. |
Unit |
@MainThreadCalled 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. |
Unit |
Called when the Fragment is visible to the user. |
Unit |
Called when the Fragment is no longer started. |
Unit |
@MainThreadCalled immediately after |
Unit |
@MainThreadCalled when all saved state has been restored into the view hierarchy of the fragment. |
Context? |
Get the |
Unit |
Postpone the entering Fragment transition until |
Unit |
postponeEnterTransition(duration: Long, timeUnit: TimeUnit)Postpone the entering Fragment transition for a given amount of time and then call |
ActivityResultLauncher<I!> |
@MainThread
Register a request to |
ActivityResultLauncher<I!> |
@MainThreadRegister a request to |
Unit |
registerForContextMenu(view: View)Registers a context menu to be shown for the given view (multiple views can show the context menu). |
Unit |
Remove a |
Unit |
This function is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an |
FragmentActivity |
Return the |
Bundle |
Return the arguments supplied when the fragment was instantiated. |
Context |
Return the |
FragmentManager |
This function is deprecated. This has been renamed to |
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 |
Unit |
Sets whether the the exit transition and enter transition overlap or not. |
Unit |
Sets whether the the return transition and reenter transition overlap or not. |
Unit |
setArguments(args: Bundle?)Supply the construction arguments for this fragment. |
Unit |
setEnterSharedElementCallback(callback: 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. |
Unit |
setEnterTransition(transition: Any?)Sets the Transition that will be used to move Views into the initial scene. |
Unit |
setExitSharedElementCallback(callback: 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. |
Unit |
setExitTransition(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. |
Unit |
This function is deprecated. This method is no longer needed when using a |
Unit |
setInitialSavedState(state: Fragment.SavedState?)Set the initial saved state that this Fragment should restore itself from when first being constructed, as returned by |
Unit |
setMenuVisibility(menuVisible: Boolean)Set a hint for whether this fragment's menu should be visible. |
Unit |
setReenterTransition(transition: Any?)Sets the Transition that will be used to move Views in to the scene when returning due to popping a back stack. |
Unit |
This function is deprecated. Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment. |
Unit |
setReturnTransition(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. |
Unit |
setSharedElementEnterTransition(transition: Any?)Sets the Transition that will be used for shared elements transferred into the content Scene. |
Unit |
setSharedElementReturnTransition(transition: Any?)Sets the Transition that will be used for shared elements transferred back during a pop of the back stack. |
Unit |
This function is deprecated. Instead of using a target fragment to pass results, the fragment requesting a result should use |
Unit |
This function is deprecated. If you are manually calling this method, use |
Boolean |
shouldShowRequestPermissionRationale(permission: String)Gets whether you should show UI with rationale before requesting a permission. |
Unit |
startActivity(intent: Intent)Call |
Unit |
startActivity(intent: Intent, options: Bundle?)Call |
Unit |
This function is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an |
Unit |
This function is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an |
Unit |
This function is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an |
Unit |
Begin postponed transitions after |
String |
toString() |
Unit |
unregisterForContextMenu(view: View)Prevents a context menu to be shown for the given view. |
Extension functions |
|
|---|---|
AuthenticationResultLauncher |
Fragment.registerForAuthenticationResult(Returns an |
AuthenticationResultLauncher |
Fragment.registerForAuthenticationResult(Returns an |
Unit |
Fragment.clearFragmentResult(requestKey: String)Clears the stored result for the given requestKey. |
Unit |
Fragment.clearFragmentResultListener(requestKey: String)Clears the stored |
ComposeView |
Fragment.content(content: @Composable () -> Unit)Wrapper function that handles the setup for creating a custom Fragment that hosts Compose content. |
NavController |
Find a |
Unit |
Fragment.setFragmentResult(requestKey: String, result: Bundle)Sets the given result for the |
Unit |
Fragment.setFragmentResultListener(Sets the |
inline NavArgsLazy<Args> |
@MainThreadReturns a |
inline Lazy<VM> |
@MainThreadReturns a property delegate to access parent activity's |
Lazy<VM> |
@MainThreadHelper method for creation of |
inline Lazy<VM> |
@MainThreadReturns a property delegate to access |
inline Lazy<VM> |
@MainThreadReturns a property delegate to access a HiltViewModel -annotated |
inline Lazy<VM> |
@MainThreadReturns a property delegate to access a HiltViewModel -annotated |
inline Lazy<VM> |
@MainThreadReturns a property delegate to access a |
inline Lazy<VM> |
@MainThreadReturns a property delegate to access a |
Public constructors
Fragment
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.
Fragment
@ContentView
Fragment(contentLayoutId: @LayoutRes Int)
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); } }
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 |
|
onCreateView |
Public functions
addOnContextAvailableListener
fun addOnContextAvailableListener(listener: OnContextAvailableListener): Unit
Add a new OnContextAvailableListener for receiving a callback for when this class is associated with a android.content.Context.
Listeners are triggered in the order they are added when added before the Context is available. Listeners added after the context has been made available will have the Context synchronously delivered to them as part of this call.
| Parameters | |
|---|---|
listener: OnContextAvailableListener |
The listener that should be added. |
| See also | |
|---|---|
removeOnContextAvailableListener |
dump
fun dump(
prefix: String,
fd: FileDescriptor?,
writer: PrintWriter,
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: FileDescriptor? |
The raw file descriptor that the dump is being sent to. |
writer: PrintWriter |
The PrintWriter to which you should dump your state. This will be closed for you after you return. |
args: Array<String!>? |
additional arguments to the dump request. |
getActivity
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 | |
|---|---|
requireActivity |
getAllowEnterTransitionOverlap
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.
| 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. |
getAllowReturnTransitionOverlap
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.
| Returns | |
|---|---|
Boolean |
true to start the reenter transition when possible or false to wait until the return transition completes. |
getArguments
fun getArguments(): Bundle?
Return the arguments supplied when the fragment was instantiated, if any.
getChildFragmentManager
fun getChildFragmentManager(): FragmentManager
Return a private FragmentManager for placing and managing Fragments inside of this Fragment.
getContext
fun getContext(): Context?
Return the Context this fragment is currently associated with.
| See also | |
|---|---|
requireContext |
getDefaultViewModelCreationExtras
@CallSuper
fun getDefaultViewModelCreationExtras(): CreationExtras
Returns the default CreationExtras that should be passed into ViewModelProvider.Factory.create when no overriding CreationExtras were passed 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 extra.
getDefaultViewModelProviderFactory
fun getDefaultViewModelProviderFactory(): ViewModelProvider.Factory
Returns the default ViewModelProvider.Factory that should be used when no custom Factory is provided to the ViewModelProvider constructors.
getEnterTransition
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 isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as entering is governed by changing visibility from INVISIBLE to VISIBLE.
| Returns | |
|---|---|
Any? |
the Transition to use to move Views into the initial Scene. |
getExitTransition
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 isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as exiting is governed by changing visibility from VISIBLE to INVISIBLE. If transition is null, the views will remain unaffected.
| Returns | |
|---|---|
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. |
fungetFragmentManager(): FragmentManager?
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 |
getHost
fun getHost(): Any?
Return the host object of this fragment. May return null if the fragment isn't currently being hosted.
| See also | |
|---|---|
requireHost |
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
fun getLayoutInflater(): LayoutInflater
Returns the cached LayoutInflater used to inflate Views of this Fragment. If onGetLayoutInflater has not been called onGetLayoutInflater will be called with a 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. |
getLifecycle
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.
getParentFragment
fun getParentFragment(): Fragment?
Returns the parent Fragment containing this Fragment. If this Fragment is attached directly to an Activity, returns null.
getParentFragmentManager
fun getParentFragmentManager(): FragmentManager
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. |
getReenterTransition
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 isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as exiting is governed by changing visibility from VISIBLE to INVISIBLE. If nothing is set, the default will be to use the same transition as getExitTransition.
| Returns | |
|---|---|
Any? |
the Transition to use to move Views into the scene when reentering from a previously-started Activity due to popping the back stack. |
fungetRetainInstance(): Boolean
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 |
getReturnTransition
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 isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as entering is governed by changing visibility from VISIBLE to INVISIBLE. If nothing is set, the default will be to use the same transition as getEnterTransition.
| Returns | |
|---|---|
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
fun getSavedStateRegistry(): SavedStateRegistry
The SavedStateRegistry owned by this SavedStateRegistryOwner
getSharedElementEnterTransition
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.
| Returns | |
|---|---|
Any? |
The Transition to use for shared elements transferred into the content Scene. |
getSharedElementReturnTransition
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.
| Returns | |
|---|---|
Any? |
The Transition to use for shared elements transferred out of the content Scene. |
getString
fun getString(resId: @StringRes Int): String
Return a localized string from the application's package's default string table.
getString
fun getString(resId: @StringRes Int, formatArgs: Array<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 format.
getText
fun getText(resId: @StringRes Int): CharSequence
Return a localized, styled CharSequence from the application's package's default string table.
fungetUserVisibleHint(): Boolean
| Returns | |
|---|---|
Boolean |
The current value of the user-visible hint on this fragment. |
| See also | |
|---|---|
setUserVisibleHint |
getView
fun getView(): View?
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. |
getViewLifecycleOwner
@MainThread
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:
createdafteronViewStateRestoredstartedafteronStartresumedafteronResumepausedbeforeonPausestoppedbeforeonStopdestroyedbeforeonDestroyView
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 runOnCommit 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 |
| Throws | |
|---|---|
java.lang.IllegalStateException |
if the |
getViewLifecycleOwnerLiveData
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.
| Returns | |
|---|---|
LiveData<LifecycleOwner!> |
A LiveData that changes in sync with |
getViewModelStore
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.
| Returns | |
|---|---|
ViewModelStore |
a |
| Throws | |
|---|---|
java.lang.IllegalStateException |
if called before the Fragment is attached i.e., before onAttach(). |
java-static funinstantiate(context: Context, fname: String): Fragment
Like instantiate but with a null argument Bundle.
java-static funinstantiate(context: Context, fname: String, args: Bundle?): 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.
| Parameters | |
|---|---|
context: Context |
The calling context being used to instantiate the fragment. This is currently just used to get its ClassLoader. |
fname: String |
The class name of the fragment to instantiate. |
args: Bundle? |
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. |
isAdded
fun isAdded(): Boolean
Return true if the fragment is currently added to its activity.
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. This includes the case if the fragment is hidden because its parent is 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
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 will fail.
| Returns | |
|---|---|
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.
@MainThread
@CallSuper
funonActivityCreated(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 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 | |
|---|---|
savedInstanceState: Bundle? |
If the fragment is being re-created from a previous saved state, this is the state. |
funonActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Unit
Receive the result from a previous call to startActivityForResult. This follows the related Activity API as described there in onActivityResult.
| 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: Intent? |
An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). |
@MainThread
@CallSuper
funonAttach(activity: Activity): Unit
Called when a fragment is first attached to its activity. onCreate will be called after this.
onAttach
@MainThread
@CallSuper
fun onAttach(context: Context): Unit
Called when a fragment is first attached to its context. onCreate will be called after this.
@MainThread
funonAttachFragment(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
fun onConfigurationChanged(newConfig: Configuration): Unit
onContextItemSelected
@MainThread
fun onContextItemSelected(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 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. |
| Returns | |
|---|---|
Boolean |
boolean Return false to allow normal context menu processing to proceed, true to consume it here. |
onCreate
@MainThread
@CallSuper
fun onCreate(savedInstanceState: Bundle?): Unit
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 CREATED callback.
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
fun onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int): Animation?
Called when a fragment loads an animation. Note that if setCustomAnimations was called with Animator resources instead of Animation resources, nextAnim will be an animator resource.
| Parameters | |
|---|---|
transit: Int |
The value set in |
enter: Boolean |
|
nextAnim: Int |
The resource set in |
onCreateAnimator
@MainThread
fun onCreateAnimator(transit: Int, enter: Boolean, nextAnim: Int): Animator?
Called when a fragment loads an animator. This will be called when onCreateAnimation returns null. Note that if setCustomAnimations was called with Animation resources instead of Animator resources, nextAnim will be an animation resource.
| Parameters | |
|---|---|
transit: Int |
The value set in |
enter: Boolean |
|
nextAnim: Int |
The resource set in |
onCreateContextMenu
@MainThread
fun onCreateContextMenu(
menu: ContextMenu,
v: View,
menuInfo: ContextMenu.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 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.
@MainThread
funonCreateOptionsMenu(menu: Menu, 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
fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
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 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 | |
|---|---|
inflater: LayoutInflater |
The LayoutInflater object that can be used to inflate any views in the fragment, |
container: ViewGroup? |
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: Bundle? |
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. |
onDestroy
@MainThread
@CallSuper
fun onDestroy(): Unit
Called when the fragment is no longer in use. This is called after onStop and before onDetach.
@MainThread
funonDestroyOptionsMenu(): 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 was not called).
onDestroyView
@MainThread
@CallSuper
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
fun onDetach(): Unit
Called when the fragment is no longer attached to its activity. This is called after onDestroy.
onGetLayoutInflater
fun onGetLayoutInflater(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. |
| Returns | |
|---|---|
LayoutInflater |
The LayoutInflater used to inflate Views of this Fragment. |
onHiddenChanged
@MainThread
fun onHiddenChanged(hidden: Boolean): Unit
Called when the hidden state (as returned by isHidden of the fragment or another fragment in its hierarchy 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. |
@UiThread
@CallSuper
funonInflate(
activity: Activity,
attrs: AttributeSet,
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.
onInflate
@UiThread
@CallSuper
fun onInflate(
context: Context,
attrs: AttributeSet,
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 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(); } }
| Parameters | |
|---|---|
context: Context |
The Activity that is inflating this fragment. |
attrs: AttributeSet |
The attributes at the tag where the fragment is being created. |
savedInstanceState: Bundle? |
If the fragment is being re-created from a previous saved state, this is the state. |
onMultiWindowModeChanged
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 onMultiWindowModeChanged of the containing Activity.
| Parameters | |
|---|---|
isInMultiWindowMode: Boolean |
True if the activity is in multi-window mode. |
@MainThread
funonOptionsItemSelected(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. |
| Returns | |
|---|---|
Boolean |
boolean Return false to allow normal menu processing to proceed, true to consume it here. |
| See also | |
|---|---|
onCreateOptionsMenu |
@MainThread
funonOptionsMenuClosed(menu: 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
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
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 onPictureInPictureModeChanged of the containing Activity.
| Parameters | |
|---|---|
isInPictureInPictureMode: Boolean |
True if the activity is in picture-in-picture mode. |
@MainThread
funonPrepareOptionsMenu(menu: 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(). |
| See also | |
|---|---|
setHasOptionsMenu |
|
onCreateOptionsMenu |
onPrimaryNavigationFragmentChanged
@MainThread
fun onPrimaryNavigationFragmentChanged(
isPrimaryNavigationFragment: 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 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 |
funonRequestPermissionsResult(
requestCode: Int,
permissions: Array<String!>,
grantResults: IntArray<Int>
): Unit
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 | |
|---|---|
requestCode: Int |
The request code passed in |
permissions: Array<String!> |
The requested permissions. Never null. |
grantResults: IntArray<Int> |
The grant results for the corresponding permissions which is either |
| See also | |
|---|---|
requestPermissions |
onResume
@MainThread
@CallSuper
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
fun onSaveInstanceState(outState: Bundle): Unit
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 | |
|---|---|
outState: Bundle |
Bundle in which to place your saved state. |
onStart
@MainThread
@CallSuper
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
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
fun onViewCreated(view: View, savedInstanceState: Bundle?): Unit
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 | |
|---|---|
view: View |
The View returned by |
savedInstanceState: Bundle? |
If non-null, this fragment is being re-constructed from a previous saved state as given here. |
onViewStateRestored
@MainThread
@CallSuper
fun onViewStateRestored(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 onViewCreated and before onStart.
| Parameters | |
|---|---|
savedInstanceState: Bundle? |
If the fragment is being re-created from a previous saved state, this is the state. |
peekAvailableContext
fun peekAvailableContext(): Context?
Get the Context if it is currently available. If this returns null, you can use addOnContextAvailableListener to receive a callback for when it available.
| Returns | |
|---|---|
Context? |
the Context if it is currently available. |
postponeEnterTransition
fun postponeEnterTransition(): Unit
Postpone the entering Fragment transition until startPostponedEnterTransition or 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.
postponeEnterTransition
fun postponeEnterTransition(duration: Long, 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, 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.
registerForActivityResult
@MainThread
fun <I, O> registerForActivityResult(
contract: ActivityResultContract<I!, O!>,
callback: ActivityResultCallback<O!>
): ActivityResultLauncher<I!>
Register a request to start an activity for result, designated by the given contract.
This creates a record in the registry associated with this caller, managing request code, as well as conversions to/from Intent under the hood.
This must be called unconditionally, as part of initialization path, typically as a field initializer of an Activity or Fragment.
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.
registerForActivityResult
@MainThread
fun <I, O> registerForActivityResult(
contract: ActivityResultContract<I!, O!>,
registry: ActivityResultRegistry,
callback: ActivityResultCallback<O!>
): ActivityResultLauncher<I!>
Register a request to start an activity for result, designated by the given contract.
This creates a record in the given registry, managing request code, as well as conversions to/from Intent under the hood.
This must be called unconditionally, as part of initialization path, typically as a field initializer of an Activity or Fragment.
| Parameters | |
|---|---|
<I> |
the type of the input(if any) required to call the activity |
<O> |
the type of output returned as an activity result |
contract: ActivityResultContract<I!, O!> |
the contract, specifying conversions to/from |
registry: ActivityResultRegistry |
the registry where to hold the record. |
callback: ActivityResultCallback<O!> |
the callback to be called on the main thread when activity result is available |
| Returns | |
|---|---|
ActivityResultLauncher<I!> |
the launcher that can be used to start the activity or dispose of the prepared call. |
registerForContextMenu
fun registerForContextMenu(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 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 | |
|---|---|
unregisterForContextMenu |
removeOnContextAvailableListener
fun removeOnContextAvailableListener(listener: OnContextAvailableListener): Unit
Remove a OnContextAvailableListener previously added via addOnContextAvailableListener.
| Parameters | |
|---|---|
listener: OnContextAvailableListener |
The listener that should be removed. |
| See also | |
|---|---|
addOnContextAvailableListener |
funrequestPermissions(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 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 onRequestPermissionsResult 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 onRequestPermissionsResult.
When checking whether you have a permission you should use checkSelfPermission.
Calling this API for permissions already granted to your app would show UI to the user to decide 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 | |
|---|---|
permissions: Array<String!> |
The requested permissions. |
requestCode: Int |
Application specific request code to match with a result reported to |
requireActivity
fun requireActivity(): FragmentActivity
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 |
requireArguments
fun requireArguments(): Bundle
Return the arguments supplied when the fragment was instantiated.
| Throws | |
|---|---|
java.lang.IllegalStateException |
if no arguments were supplied to the Fragment. |
| See also | |
|---|---|
getArguments |
requireContext
fun requireContext(): Context
Return the Context this fragment is currently associated with.
| Throws | |
|---|---|
java.lang.IllegalStateException |
if not currently associated with a context. |
| See also | |
|---|---|
getContext |
funrequireFragmentManager(): FragmentManager
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 |
requireHost
fun requireHost(): Any
Return the host object of this fragment.
| Throws | |
|---|---|
java.lang.IllegalStateException |
if not currently associated with a host. |
| See also | |
|---|---|
getHost |
requireParentFragment
fun requireParentFragment(): Fragment
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 |
requireView
fun requireView(): View
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 |
setAllowEnterTransitionOverlap
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
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
fun setArguments(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
fun setEnterSharedElementCallback(callback: 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
fun setEnterTransition(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 isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as entering is governed by changing visibility from INVISIBLE to VISIBLE. If transition is null, entering Views will remain unaffected.
| Parameters | |
|---|---|
transition: Any? |
The Transition to use to move Views into the initial Scene. |
setExitSharedElementCallback
fun setExitSharedElementCallback(callback: 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
fun setExitTransition(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 isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as exiting is governed by changing visibility from VISIBLE to 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. |
funsetHasOptionsMenu(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
fun setInitialSavedState(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
fun setMenuVisibility(menuVisible: 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
fun setReenterTransition(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 isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as exiting is governed by changing visibility from VISIBLE to 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. |
funsetRetainInstance(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:
onDestroywill not be called (butonDetachstill will be, because the fragment is being detached from its current activity).onCreatewill not be called since the fragment is not being re-created.onAttachandonActivityCreatedwill still be called.
| Parameters | |
|---|---|
retain: Boolean |
|
| See also | |
|---|---|
getRetainInstance |
setReturnTransition
fun setReturnTransition(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 isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as entering is governed by changing visibility from VISIBLE to 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.
| 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. |
setSharedElementEnterTransition
fun setSharedElementEnterTransition(transition: 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. |
setSharedElementReturnTransition
fun setSharedElementReturnTransition(transition: 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.
| Parameters | |
|---|---|
transition: Any? |
The Transition to use for shared elements transferred out of the content Scene. |
funsetTargetFragment(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: Int |
Optional request code, for convenience if you are going to call back with |
funsetUserVisibleHint(isVisibleToUser: Boolean): Unit
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
fun shouldShowRequestPermissionRationale(permission: String): Boolean
Gets whether you should show UI with rationale before requesting a permission.
| Parameters | |
|---|---|
permission: String |
A permission your app wants to request. |
| Returns | |
|---|---|
Boolean |
Whether you should show permission rationale UI. |
startActivity
fun startActivity(intent: Intent): Unit
Call startActivity from the fragment's containing Activity.
startActivity
fun startActivity(intent: Intent, options: Bundle?): Unit
Call startActivity from the fragment's containing Activity.
funstartActivityForResult(intent: Intent, requestCode: Int): Unit
Call startActivityForResult from the fragment's containing Activity.
| Parameters | |
|---|---|
intent: Intent |
The intent to start. |
requestCode: Int |
The request code to be returned in |
funstartActivityForResult(intent: Intent, requestCode: Int, options: Bundle?): Unit
Call startActivityForResult from the fragment's containing Activity.
| Parameters | |
|---|---|
intent: Intent |
The intent to start. |
requestCode: Int |
The request code to be returned in |
options: Bundle? |
Additional options for how the Activity should be started. See |
funstartIntentSenderForResult(
intent: IntentSender,
requestCode: Int,
fillInIntent: Intent?,
flagsMask: Int,
flagsValues: Int,
extraFlags: Int,
options: Bundle?
): Unit
Call startIntentSenderForResult from the fragment's containing Activity.
| Parameters | |
|---|---|
intent: IntentSender |
The IntentSender to launch. |
requestCode: Int |
The request code to be returned in |
fillInIntent: Intent? |
If non-null, this will be provided as the intent parameter to |
flagsMask: Int |
Intent flags in the original IntentSender that you would like to change. |
flagsValues: Int |
Desired values for any bits set in |
extraFlags: Int |
Always set to 0. |
options: Bundle? |
Additional options for how the Activity should be started. See |
startPostponedEnterTransition
fun startPostponedEnterTransition(): Unit
Begin postponed transitions after postponeEnterTransition was called. If postponeEnterTransition() was called, you must call startPostponedEnterTransition() or executePendingTransactions to complete the FragmentTransaction. If postponement was interrupted with executePendingTransactions, before startPostponedEnterTransition(), animations may not run or may execute improperly.
| See also | |
|---|---|
startPostponedEnterTransition |
unregisterForContextMenu
fun unregisterForContextMenu(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 | |
|---|---|
registerForContextMenu |
Extension functions
Fragment.registerForAuthenticationResult
fun Fragment.registerForAuthenticationResult(
resultCallback: AuthenticationResultCallback
): AuthenticationResultLauncher
Returns an AuthenticationResultLauncher that can be used to initiate authentication.
A success or error result will be delivered to AuthenticationResultCallback.onAuthResult and (one or more) failures will be delivered to AuthenticationResultCallback.onAuthAttemptFailed, which is set by resultCallback. The callback will be executed on the main thread.
This must be called unconditionally, as part of initialization path, typically as a field initializer of an Fragment.
Note that if multiple calls to this method are made within a single Fragment or Activity, only the callback registered by the last invocation will be saved and receive authentication results. This can result in unexpected behavior if you intend to manage multiple independent authentication flows. It is strongly recommended to avoid multiple calls to this method in such scenarios.
import androidx.biometric.AuthenticationRequest import androidx.biometric.AuthenticationRequest.Biometric import androidx.biometric.AuthenticationRequest.Companion.biometricRequest import androidx.biometric.AuthenticationResult import androidx.biometric.PromptContentItemBulletedText import androidx.biometric.registerForAuthenticationResult import androidx.fragment.app.Fragment class MyFragmentForCredentialOnlyAuth : Fragment() { val requestAuthentication = registerForAuthenticationResult { result: AuthenticationResult -> when (result) { // Handle successful authentication is AuthenticationResult.Success -> { Log.i(TAG, "onAuthenticationSucceeded with type ${result.authType}") } // Handle authentication error, e.g. user cancellation, lockout errors, etc is AuthenticationResult.Error -> { Log.i( TAG, "onAuthenticationError " + "with error code: ${result.errorCode} " + "and error string: ${result.errString}", ) } // Handle fallback option clicks is AuthenticationResult.CustomFallbackSelected -> { Log.i(TAG, "fallback is selected, text: ${result.fallback.text}") } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val authRequest = biometricRequest(title = "Title", Biometric.Fallback.DeviceCredential) { setSubtitle("Subtitle") setContent( AuthenticationRequest.BodyContent.VerticalList( "Vertical list description", listOf( PromptContentItemBulletedText("test item1"), PromptContentItemBulletedText("test item2"), ), ) ) setMinStrength(Biometric.Strength.Class3(/*optional: cryptoObject*/ )) setIsConfirmationRequired(true) } Button(context).setOnClickListener { requestAuthentication.launch(authRequest) } } }
| See also | |
|---|---|
registerForAuthenticationResult |
(Executor, AuthenticationResultCallback) |
Fragment.registerForAuthenticationResult
fun Fragment.registerForAuthenticationResult(
callbackExecutor: Executor,
resultCallback: AuthenticationResultCallback
): AuthenticationResultLauncher
Returns an AuthenticationResultLauncher that can be used to initiate authentication.
A success or error result will be delivered to AuthenticationResultCallback.onAuthResult and (one or more) failures will be delivered to AuthenticationResultCallback.onAuthAttemptFailed, which is set by resultCallback. The callback will be executed on the thread provided by the callbackExecutor.
This must be called unconditionally, as part of initialization path, typically as a field initializer of an Fragment.
Note that if multiple calls to this method are made within a single Fragment or Activity, only the callback registered by the last invocation will be saved and receive authentication results. This can result in unexpected behavior if you intend to manage multiple independent authentication flows. It is strongly recommended to avoid multiple calls to this method in such scenarios.
import androidx.biometric.AuthenticationRequest import androidx.biometric.AuthenticationRequest.Biometric import androidx.biometric.AuthenticationRequest.Companion.biometricRequest import androidx.biometric.AuthenticationResult import androidx.biometric.PromptContentItemBulletedText import androidx.biometric.registerForAuthenticationResult import androidx.fragment.app.Fragment class MyFragmentForCredentialOnlyAuth : Fragment() { val requestAuthentication = registerForAuthenticationResult { result: AuthenticationResult -> when (result) { // Handle successful authentication is AuthenticationResult.Success -> { Log.i(TAG, "onAuthenticationSucceeded with type ${result.authType}") } // Handle authentication error, e.g. user cancellation, lockout errors, etc is AuthenticationResult.Error -> { Log.i( TAG, "onAuthenticationError " + "with error code: ${result.errorCode} " + "and error string: ${result.errString}", ) } // Handle fallback option clicks is AuthenticationResult.CustomFallbackSelected -> { Log.i(TAG, "fallback is selected, text: ${result.fallback.text}") } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val authRequest = biometricRequest(title = "Title", Biometric.Fallback.DeviceCredential) { setSubtitle("Subtitle") setContent( AuthenticationRequest.BodyContent.VerticalList( "Vertical list description", listOf( PromptContentItemBulletedText("test item1"), PromptContentItemBulletedText("test item2"), ), ) ) setMinStrength(Biometric.Strength.Class3(/*optional: cryptoObject*/ )) setIsConfirmationRequired(true) } Button(context).setOnClickListener { requestAuthentication.launch(authRequest) } } }
Fragment.clearFragmentResult
fun Fragment.clearFragmentResult(requestKey: String): Unit
Clears the stored result for the given requestKey.
This clears a result that was previously set a call to setFragmentResult.
If this is called with a requestKey that is not associated with any result, this method does nothing.
| Parameters | |
|---|---|
requestKey: String |
key used to identify the result |
Fragment.clearFragmentResultListener
fun Fragment.clearFragmentResultListener(requestKey: String): Unit
Clears the stored FragmentResultListener for the given requestKey.
This clears a FragmentResultListener that was previously set a call to setFragmentResultListener.
If this is called with a requestKey that is not associated with any FragmentResultListener, this method does nothing.
| Parameters | |
|---|---|
requestKey: String |
key used to identify the result |
Fragment.content
fun Fragment.content(content: @Composable () -> Unit): ComposeView
Wrapper function that handles the setup for creating a custom Fragment that hosts Compose content. It automatically sets the ViewCompositionStrategy to ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed.
It should be used as part of the implementation of Fragment.onCreateView and requires a context meaning the fragment must be attached to a FragmentManager.
class ExampleFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
) = content {
val viewModel: ExampleViewModel = viewModel()
// put your @Composable content here
}
}
Fragment.findNavController
fun Fragment.findNavController(): NavController
Find a NavController given a Fragment
Calling this on a Fragment that is not a NavHostFragment or within a NavHostFragment will result in an IllegalStateException
Fragment.setFragmentResult
fun Fragment.setFragmentResult(requestKey: String, result: Bundle): Unit
Sets the given result for the requestKey. This result will be delivered to a FragmentResultListener that is called given to setFragmentResultListener with the same requestKey. If no FragmentResultListener with the same key is set or the Lifecycle associated with the listener is not at least androidx.lifecycle.Lifecycle.State.STARTED, the result is stored until one becomes available, or clearFragmentResult is called with the same requestKey.
Fragment.setFragmentResultListener
fun Fragment.setFragmentResultListener(
requestKey: String,
listener: (requestKey: String, bundle: Bundle) -> Unit
): Unit
Sets the FragmentResultListener for a given requestKey. Once this Fragment is at least in the androidx.lifecycle.Lifecycle.State.STARTED state, any results set by setFragmentResult using the same requestKey will be delivered to the FragmentResultListener.onFragmentResult callback. The callback will remain active until this Fragment reaches the androidx.lifecycle.Lifecycle.State.DESTROYED state or clearFragmentResultListener is called with the same requestKey.
Fragment.navArgs
@MainThread
inline fun <Args : NavArgs> Fragment.navArgs(): NavArgsLazy<Args>
Returns a Lazy delegate to access the Fragment's arguments as an Args instance.
It is strongly recommended that this method only be used when the Fragment is created by androidx.navigation.NavController.navigate with the corresponding androidx.navigation.NavDirections object, which ensures that the required arguments are present.
class MyFragment : Fragment() {
val args: MyFragmentArgs by navArgs()
}
This property can be accessed only after the Fragment's constructor.
Fragment.activityViewModels
@MainThread
inline fun <VM : ViewModel> Fragment.activityViewModels(
noinline extrasProducer: (() -> CreationExtras)? = null,
noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null
): Lazy<VM>
Returns a property delegate to access parent activity's ViewModel, if factoryProducer is specified then ViewModelProvider.Factory returned by it will be used to create ViewModel first time. Otherwise, the activity's default factory will be used.
class MyFragment : Fragment() {
val viewmodel: MyViewModel by activityViewModels()
}
This property can be accessed only after this Fragment is attached i.e., after Fragment.onAttach(), and access prior to that will result in IllegalArgumentException.
Fragment.createViewModelLazy
@MainThread
fun <VM : ViewModel> Fragment.createViewModelLazy(
viewModelClass: KClass<VM>,
storeProducer: () -> ViewModelStore,
extrasProducer: () -> CreationExtras = { defaultViewModelCreationExtras },
factoryProducer: (() -> ViewModelProvider.Factory)? = null
): Lazy<VM>
Helper method for creation of ViewModelLazy, that resolves null passed as factoryProducer to the default factory.
This method also takes a CreationExtras producer that provides default extras to the created ViewModel.
Fragment.viewModels
@MainThread
inline fun <VM : ViewModel> Fragment.viewModels(
noinline ownerProducer: () -> ViewModelStoreOwner = { this },
noinline extrasProducer: (() -> CreationExtras)? = null,
noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null
): Lazy<VM>
Returns a property delegate to access ViewModel by default scoped to this Fragment:
class MyFragment : Fragment() {
val viewmodel: MyViewModel by viewModels()
}
Custom ViewModelProvider.Factory can be defined via factoryProducer parameter, factory returned by it will be used to create ViewModel:
class MyFragment : Fragment() {
val viewmodel: MyViewModel by viewModels { myFactory }
}
Default scope may be overridden with parameter ownerProducer:
class MyFragment : Fragment() {
val viewmodel: MyViewModel by viewModels ({requireParentFragment()})
}
This property can be accessed only after this Fragment is attached i.e., after Fragment.onAttach(), and access prior to that will result in IllegalArgumentException.
Fragment.hiltNavGraphViewModels
@MainThread
inline fun <VM : ViewModel> Fragment.hiltNavGraphViewModels(navGraphId: @IdRes Int): Lazy<VM>
Returns a property delegate to access a HiltViewModel -annotated ViewModel scoped to a navigation graph present on the androidx.navigation.NavController back stack:
class MyFragment : Fragment() {
val viewmodel: MainViewModel by hiltNavGraphViewModels(R.navigation.main)
}
This property can be accessed only after this NavGraph is on the NavController back stack, and an attempt access prior to that will result in an IllegalArgumentException.
| Parameters | |
|---|---|
navGraphId: @IdRes Int |
ID of a NavGraph that exists on the |
Fragment.hiltNavGraphViewModels
@MainThread
inline fun <VM : ViewModel, VMF : Any> Fragment.hiltNavGraphViewModels(
navGraphId: @IdRes Int,
noinline creationCallback: (VMF) -> VM
): Lazy<VM>
Returns a property delegate to access a HiltViewModel -annotated ViewModel with an @AssistedInject-annotated constructor that is scoped to a navigation graph present on the androidx.navigation.NavController back stack:
class MyFragment : Fragment() {
val viewmodel: MainViewModel by hiltNavGraphViewModels(R.navigation.main) { factory: MainViewModelFactory ->
factory.create(...)
}
}
This property can be accessed only after this NavGraph is on the NavController back stack, and an attempt access prior to that will result in an IllegalArgumentException.
| Parameters | |
|---|---|
navGraphId: @IdRes Int |
ID of a NavGraph that exists on the |
noinline creationCallback: (VMF) -> VM |
callback that takes an @AssistedFactory-annotated factory and creates a HiltViewModel using @AssistedInject-annotated constructor. |
Fragment.navGraphViewModels
@MainThread
inline fun <VM : ViewModel> Fragment.navGraphViewModels(
navGraphId: @IdRes Int,
noinline extrasProducer: (() -> CreationExtras)? = null,
noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null
): Lazy<VM>
Returns a property delegate to access a ViewModel scoped to a navigation graph present on the NavController back stack:
class MyFragment : Fragment() {
val viewmodel: MainViewModel by navGraphViewModels(R.id.main)
}
Custom ViewModelProvider.Factory can be defined via factoryProducer parameter, factory returned by it will be used to create ViewModel:
class MyFragment : Fragment() {
val viewmodel: MainViewModel by navGraphViewModels(R.id.main) { myFactory }
}
This property can be accessed only after this NavGraph is on the NavController back stack, and an attempt access prior to that will result in an IllegalArgumentException.
| Parameters | |
|---|---|
navGraphId: @IdRes Int |
ID of a NavGraph that exists on the |
noinline extrasProducer: (() -> CreationExtras)? = null |
lambda that will be called during initialization to return |
noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null |
lambda that will be called during initialization to return |
Fragment.navGraphViewModels
@MainThread
inline fun <VM : ViewModel> Fragment.navGraphViewModels(
navGraphRoute: String,
noinline extrasProducer: (() -> CreationExtras)? = null,
noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null
): Lazy<VM>
Returns a property delegate to access a ViewModel scoped to a navigation graph present on the NavController back stack:
class MyFragment : Fragment() {
val viewModel: MainViewModel by navGraphViewModels("main")
}
Custom ViewModelProvider.Factory can be defined via factoryProducer parameter, factory returned by it will be used to create ViewModel:
class MyFragment : Fragment() {
val viewModel: MainViewModel by navGraphViewModels("main") { myFactory }
}
This property can be accessed only after this NavGraph is on the NavController back stack, and an attempt access prior to that will result in an IllegalArgumentException.
| Parameters | |
|---|---|
navGraphRoute: String |
|
noinline extrasProducer: (() -> CreationExtras)? = null |
lambda that will be called during initialization to return |
noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null |
lambda that will be called during initialization to return |