Fragment

class Fragment : ComponentCallbacks, View.OnCreateContextMenuListener, LifecycleOwner, ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner, ActivityResultCaller

Known direct subclasses
AbstractListDetailFragment

A fragment supports adaptive two-pane layout.

AbstractProgressFragment

The base class for Fragments that handle dynamic feature installation.

AmbientModeSupport

This class is deprecated.

Use AmbientLifecycleObserver instead.

BrandedSupportFragment

Fragment class for managing search and branding using a view that implements TitleViewAdapter.Provider.

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 DialogPreference, for example or androidx.preference.MultiSelectListPreference.

LeanbackSettingsFragmentCompat

This fragment provides a container for displaying a LeanbackPreferenceFragmentCompat

ListFragment

Static library support version of the framework's android.app.ListFragment.

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.

PlaybackSupportFragment

A fragment for displaying playback controls and related content.

PreferenceFragmentCompat

A PreferenceFragmentCompat is the entry point to using the Preference library.

PreferenceHeaderFragmentCompat

PreferenceHeaderFragmentCompat implements a two-pane fragment for preferences.

RowsSupportFragment

An ordered set of rows of leanback widgets.

SearchSupportFragment

A fragment to handle searches.

Known indirect subclasses
AppCompatDialogFragment

A special version of DialogFragment which uses an AppCompatDialog in place of a platform-styled dialog.

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.

DefaultProgressFragment

The default androidx.fragment.app.Fragment to display during installation progress.

DetailsSupportFragment

A fragment for creating Leanback details screens.

DynamicNavHostFragment

The NavHostFragment for dynamic features.

EditTextPreferenceDialogFragmentCompat
ErrorSupportFragment

A fragment for displaying an error indication.

LeanbackEditTextPreferenceDialogFragmentCompat

Implemented a dialog to input text.

LeanbackListPreferenceDialogFragmentCompat

Implemented a dialog to show ListPreference or MultiSelectListPreference.

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 DialogPreference.

VerticalGridSupportFragment

A fragment for creating leanback vertical grids.

VideoSupportFragment

Subclass of PlaybackSupportFragment that is responsible for providing a SurfaceView and rendering video.


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:

Summary

Nested types

Thrown by instantiate when there is an instantiation failure.

State information that has been retrieved from a fragment instance through FragmentManager.saveFragmentInstanceState.

Public constructors

Constructor used by the default FragmentFactory.

@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.

Public functions

Unit
dump(
    prefix: String,
    fd: FileDescriptor?,
    writer: PrintWriter,
    args: Array<String!>?
)

Print the Fragments's state into the given stream.

Boolean
equals(o: Any?)

Subclasses can not override equals().

FragmentActivity?

Return the FragmentActivity this fragment is currently associated with.

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 Context this fragment is currently associated with.

CreationExtras

Returns the default CreationExtras that should be passed into ViewModelProvider.Factory.create when no overriding CreationExtras were passed to the ViewModelProvider constructors.

ViewModelProvider.Factory

Returns the default ViewModelProvider.Factory that should be used when no custom Factory is provided to the ViewModelProvider constructors.

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 getParentFragmentManager() which throws an IllegalStateException if the FragmentManager is null.

Any?

Return the host object of this fragment.

Int

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.

Use LoaderManager.getInstance(this).

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 requireActivity().getResources().

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 SavedStateRegistry owned by this SavedStateRegistryOwner

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
getString(resId: @StringRes Int, formatArgs: Array<Any!>?)

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.

String?

Get the tag name of the fragment, if specified.

Fragment?

This function is deprecated.

Instead of using a target fragment to pass results, use setFragmentResult to deliver results to FragmentResultListener instances registered by other fragments via setFragmentResultListener.

Int

This function is deprecated.

When using the target fragment replacement of setFragmentResultListener and setFragmentResult, consider using setArguments to pass a requestKey if you need to support dynamic request keys.

CharSequence

Return a localized, styled CharSequence from the application's package's default string table.

Boolean

This function is deprecated.

Use setMaxLifecycle instead.

View?

Get the root view for the fragment's layout (the one returned by onCreateView), if provided.

LifecycleOwner

Get a LifecycleOwner that represents the Fragment's View lifecycle.

LiveData<LifecycleOwner!>

Retrieve a LiveData which allows you to observe the lifecycle of the Fragment's View.

ViewModelStore

Returns the ViewModelStore associated with this Fragment

Int

Subclasses can not override hashCode().

java-static Fragment
instantiate(context: Context, fname: String)

This function is deprecated.

Use getFragmentFactory and instantiate

java-static Fragment
instantiate(context: Context, fname: String, args: Bundle?)

This function is deprecated.

Use getFragmentFactory and instantiate, manually calling setArguments on the returned Fragment.

Boolean

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

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 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.

Unit

This function is deprecated.

use onViewCreated for code touching the view created by onCreateView and onCreate for other initialization.

Unit
onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)

This function is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

Unit

This function is deprecated.

See onAttach.

Unit

Called when a fragment is first attached to its context.

Unit

This function is deprecated.

The responsibility for listening for fragments being attached has been moved to FragmentManager.

Unit
Boolean

This hook is called whenever an item in a context menu is selected.

Unit
@MainThread
@CallSuper
onCreate(savedInstanceState: Bundle?)

Called to do initial creation of a fragment.

Animation?
@MainThread
onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int)

Called when a fragment loads an animation.

Animator?
@MainThread
onCreateAnimator(transit: Int, enter: Boolean, nextAnim: Int)

Called when a fragment loads an animator.

Unit
@MainThread
onCreateContextMenu(
    menu: ContextMenu,
    v: View,
    menuInfo: ContextMenu.ContextMenuInfo?
)

Called when a context menu for the view is about to be shown.

Unit

This function is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

View?
@MainThread
onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
)

Called to have the fragment instantiate its user interface view.

Unit

Called when the fragment is no longer in use.

Unit

This function is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

Unit

Called when the view previously created by onCreateView has been detached from the fragment.

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

Called when the hidden state (as returned by isHidden of the fragment or another fragment in its hierarchy has changed.

Unit
@UiThread
@CallSuper
onInflate(
    activity: Activity,
    attrs: AttributeSet,
    savedInstanceState: Bundle?
)

This function is deprecated.

See onInflate.

Unit
@UiThread
@CallSuper
onInflate(
    context: Context,
    attrs: AttributeSet,
    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.

Unit
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.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

Unit

This function is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

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

This function is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

Unit
@MainThread
onPrimaryNavigationFragmentChanged(
    isPrimaryNavigationFragment: Boolean
)

Callback for when the primary navigation state of this Fragment has changed.

Unit
onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<String!>,
    grantResults: IntArray
)

This function is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

Unit

Called when the fragment is visible to the user and actively running.

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.

Unit

Called when the Fragment is visible to the user.

Unit

Called when the Fragment is no longer started.

Unit
@MainThread
onViewCreated(view: View, savedInstanceState: Bundle?)

Called immediately after onCreateView has returned, but before any saved state has been restored in to the view.

Unit

Called when all saved state has been restored into the view hierarchy of the fragment.

Unit

Postpone the entering Fragment transition until startPostponedEnterTransition or executePendingTransactions has been called.

Unit
postponeEnterTransition(duration: Long, timeUnit: TimeUnit)

Postpone the entering Fragment transition for a given amount of time and then call startPostponedEnterTransition.

ActivityResultLauncher<I!>
@MainThread
<I, O> registerForActivityResult(
    contract: ActivityResultContract<I!, O!>,
    callback: ActivityResultCallback<O!>
)

Register a request to start an activity for result, designated by the given contract.

ActivityResultLauncher<I!>
@MainThread
<I, O> registerForActivityResult(
    contract: ActivityResultContract<I!, O!>,
    registry: ActivityResultRegistry,
    callback: ActivityResultCallback<O!>
)

Register a request to start an activity for result, designated by the given contract.

Unit

Registers a context menu to be shown for the given view (multiple views can show the context menu).

Unit
requestPermissions(permissions: Array<String!>, requestCode: Int)

This function is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

FragmentActivity

Return the FragmentActivity this fragment is currently associated with.

Bundle

Return the arguments supplied when the fragment was instantiated.

Context

Return the Context this fragment is currently associated with.

FragmentManager

This function is 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.

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 onCreateView).

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

Supply the construction arguments for this fragment.

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.

Unit
setEnterTransition(transition: Any?)

Sets the Transition that will be used to move Views into the initial scene.

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.

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 MenuProvider to provide a Menu to your activity, which replaces onCreateOptionsMenu as the recommended way to provide a consistent, optionally Lifecycle-aware, and modular way to handle menu creation and item selection.

Unit

Set the initial saved state that this Fragment should restore itself from when first being constructed, as returned by FragmentManager.saveFragmentInstanceState.

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

Sets the Transition that will be used for shared elements transferred into the content Scene.

Unit

Sets the Transition that will be used for shared elements transferred back during a pop of the back stack.

Unit
setTargetFragment(fragment: Fragment?, requestCode: Int)

This function is deprecated.

Instead of using a target fragment to pass results, the fragment requesting a result should use setFragmentResultListener to register a FragmentResultListener with a requestKey using its parent fragment manager.

Unit
setUserVisibleHint(isVisibleToUser: Boolean)

This function is deprecated.

If you are manually calling this method, use setMaxLifecycle instead.

Boolean

Gets whether you should show UI with rationale before requesting a permission.

Unit

Call startActivity from the fragment's containing Activity.

Unit
startActivity(intent: Intent, options: Bundle?)

Call startActivity from the fragment's containing Activity.

Unit
startActivityForResult(intent: Intent, requestCode: Int)

This function is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

Unit
startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?)

This function is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

Unit
startIntentSenderForResult(
    intent: IntentSender,
    requestCode: Int,
    fillInIntent: Intent?,
    flagsMask: Int,
    flagsValues: Int,
    extraFlags: Int,
    options: Bundle?
)

This function is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

Unit

Begin postponed transitions after postponeEnterTransition was called.

String
Unit

Prevents a context menu to be shown for the given view.

Extension functions

suspend BiometricPrompt.AuthenticationResult
Fragment.authenticateWithClass2Biometrics(
    title: CharSequence,
    negativeButtonText: CharSequence,
    subtitle: CharSequence?,
    description: CharSequence?,
    confirmationRequired: Boolean
)

Prompts the user to authenticate with a Class 2 biometric (e.g. fingerprint, face, or iris).

AuthPrompt
Fragment.startClass2BiometricAuthentication(
    title: CharSequence,
    negativeButtonText: CharSequence,
    subtitle: CharSequence?,
    description: CharSequence?,
    confirmationRequired: Boolean,
    executor: Executor?,
    callback: AuthPromptCallback
)

Prompts the user to authenticate with a Class 2 biometric (e.g. fingerprint, face, or iris).

suspend BiometricPrompt.AuthenticationResult
Fragment.authenticateWithClass2BiometricsOrCredentials(
    title: CharSequence,
    subtitle: CharSequence?,
    description: CharSequence?,
    confirmationRequired: Boolean
)

Prompts the user to authenticate with a Class 2 biometric (e.g. fingerprint, face, or iris) or the screen lock credential (i.e. PIN, pattern, or password) for the device.

AuthPrompt
Fragment.startClass2BiometricOrCredentialAuthentication(
    title: CharSequence,
    subtitle: CharSequence?,
    description: CharSequence?,
    confirmationRequired: Boolean,
    executor: Executor?,
    callback: AuthPromptCallback
)

Prompts the user to authenticate with a Class 2 biometric (e.g. fingerprint, face, or iris) or the screen lock credential (i.e. PIN, pattern, or password) for the device.

suspend BiometricPrompt.AuthenticationResult
Fragment.authenticateWithClass3Biometrics(
    crypto: BiometricPrompt.CryptoObject?,
    title: CharSequence,
    negativeButtonText: CharSequence,
    subtitle: CharSequence?,
    description: CharSequence?,
    confirmationRequired: Boolean
)

Prompts the user to authenticate with a Class 3 biometric (e.g. fingerprint, face, or iris).

AuthPrompt
Fragment.authenticateWithClass3Biometrics(
    crypto: BiometricPrompt.CryptoObject?,
    title: CharSequence,
    negativeButtonText: CharSequence,
    subtitle: CharSequence?,
    description: CharSequence?,
    confirmationRequired: Boolean,
    executor: Executor?,
    callback: AuthPromptCallback
)

Prompts the user to authenticate with a Class 3 biometric (e.g. fingerprint, face, or iris).

suspend BiometricPrompt.AuthenticationResult
@RequiresApi(value = 30)
Fragment.authenticateWithClass3BiometricsOrCredentials(
    crypto: BiometricPrompt.CryptoObject?,
    title: CharSequence,
    subtitle: CharSequence?,
    description: CharSequence?,
    confirmationRequired: Boolean
)

Prompts the user to authenticate with a Class 3 biometric (e.g. fingerprint, face, or iris) or the screen lock credential (i.e. PIN, pattern, or password) for the device.

AuthPrompt
@RequiresApi(value = 30)
Fragment.startClass3BiometricOrCredentialAuthentication(
    crypto: BiometricPrompt.CryptoObject?,
    title: CharSequence,
    subtitle: CharSequence?,
    description: CharSequence?,
    confirmationRequired: Boolean,
    executor: Executor?,
    callback: AuthPromptCallback
)

Prompts the user to authenticate with a Class 3 biometric (e.g. fingerprint, face, or iris) or the screen lock credential (i.e. PIN, pattern, or password) for the device.

suspend BiometricPrompt.AuthenticationResult
@RequiresApi(value = 30)
Fragment.authenticateWithCredentials(
    crypto: BiometricPrompt.CryptoObject?,
    title: CharSequence,
    description: CharSequence?
)

Prompts the user to authenticate with the screen lock credential (i.e. PIN, pattern, or password) for the device.

AuthPrompt
@RequiresApi(value = 30)
Fragment.startCredentialAuthentication(
    crypto: BiometricPrompt.CryptoObject?,
    title: CharSequence,
    description: CharSequence?,
    executor: Executor?,
    callback: AuthPromptCallback
)

Prompts the user to authenticate with the screen lock credential (i.e. PIN, pattern, or password) for the device.

Unit

Clears the stored result for the given requestKey.

Unit

Clears the stored FragmentResultListener for the given requestKey.

<Error class: unknown class>
Fragment.content(content: @Composable () -> Unit)

Wrapper function that handles the setup for creating a custom Fragment that hosts Compose content.

NavController

Find a NavController given a Fragment

Unit
Fragment.setFragmentResult(requestKey: String, result: Bundle)

Sets the given result for the requestKey.

Unit
Fragment.setFragmentResultListener(
    requestKey: String,
    listener: (requestKey: String, bundle: Bundle) -> Unit
)

Sets the FragmentResultListener for a given requestKey.

inline NavArgsLazy<Args>

Returns a Lazy delegate to access the Fragment's arguments as an Args instance.

inline Lazy<VM>
@MainThread
<VM : ViewModel> Fragment.activityViewModels(
    noinline extrasProducer: (() -> CreationExtras)?,
    noinline factoryProducer: (() -> ViewModelProvider.Factory)?
)

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.

Lazy<VM>
@MainThread
<VM : ViewModel> Fragment.createViewModelLazy(
    viewModelClass: KClass<VM>,
    storeProducer: () -> ViewModelStore,
    extrasProducer: () -> CreationExtras,
    factoryProducer: (() -> ViewModelProvider.Factory)?
)

Helper method for creation of ViewModelLazy, that resolves null passed as factoryProducer to default factory.

inline Lazy<VM>
@MainThread
<VM : ViewModel> Fragment.viewModels(
    noinline ownerProducer: () -> ViewModelStoreOwner,
    noinline extrasProducer: (() -> CreationExtras)?,
    noinline factoryProducer: (() -> ViewModelProvider.Factory)?
)

Returns a property delegate to access ViewModel by default scoped to this Fragment:

inline Lazy<VM>

Returns a property delegate to access a HiltViewModel -annotated ViewModel scoped to a navigation graph present on the NavController back stack:

inline Lazy<VM>
@MainThread
<VM : ViewModel, VMF : Any> Fragment.hiltNavGraphViewModels(
    navGraphId: @IdRes Int,
    noinline creationCallback: (VMF) -> 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 NavController back stack:

inline Lazy<VM>
@MainThread
<VM : ViewModel> Fragment.navGraphViewModels(
    navGraphId: @IdRes Int,
    noinline extrasProducer: (() -> CreationExtras)?,
    noinline factoryProducer: (() -> ViewModelProvider.Factory)?
)

Returns a property delegate to access a ViewModel scoped to a navigation graph present on the NavController back stack:

inline Lazy<VM>
@MainThread
<VM : ViewModel> Fragment.navGraphViewModels(
    navGraphRoute: String,
    noinline extrasProducer: (() -> CreationExtras)?,
    noinline factoryProducer: (() -> ViewModelProvider.Factory)?
)

Returns a property delegate to access a ViewModel scoped to a navigation graph present on the NavController back stack:

Public constructors

Fragment

Added in 1.1.0
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

Added in 1.1.0
@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);
  }
}
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.

Public functions

dump

Added in 1.1.0
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.

equals

Added in 1.1.0
fun equals(o: Any?): Boolean

Subclasses can not override equals().

getActivity

Added in 1.1.0
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

Added in 1.1.0
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

Added in 1.1.0
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

Added in 1.1.0
fun getArguments(): Bundle?

Return the arguments supplied when the fragment was instantiated, if any.

getChildFragmentManager

Added in 1.1.0
fun getChildFragmentManager(): FragmentManager

Return a private FragmentManager for placing and managing Fragments inside of this Fragment.

getContext

Added in 1.1.0
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

Added in 1.2.0
fun getDefaultViewModelProviderFactory(): ViewModelProvider.Factory

Returns the default ViewModelProvider.Factory that should be used when no custom Factory is provided to the ViewModelProvider constructors.

getEnterTransition

Added in 1.1.0
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

Added in 1.1.0
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.

getFragmentManager

Added in 1.1.0
Deprecated in 1.2.0
fun getFragmentManager(): 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.

getHost

Added in 1.1.0
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

Added in 1.1.0
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

Added in 1.1.0
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

Added in 1.1.0
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.

getLoaderManager

Added in 1.1.0
Deprecated in 1.1.0
fun getLoaderManager(): LoaderManager

Return the LoaderManager for this fragment.

getParentFragment

Added in 1.1.0
fun getParentFragment(): Fragment?

Returns the parent Fragment containing this Fragment. If this Fragment is attached directly to an Activity, returns null.

getParentFragmentManager

Added in 1.2.0
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

Added in 1.1.0
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.

getResources

Added in 1.1.0
fun getResources(): Resources

Return requireActivity().getResources().

getRetainInstance

Added in 1.1.0
Deprecated in 1.3.0
fun getRetainInstance(): 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.

getReturnTransition

Added in 1.1.0
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

Added in 1.1.0
fun getSavedStateRegistry(): SavedStateRegistry

The SavedStateRegistry owned by this SavedStateRegistryOwner

getSharedElementEnterTransition

Added in 1.1.0
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

Added in 1.1.0
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

Added in 1.1.0
fun getString(resId: @StringRes Int): String

Return a localized string from the application's package's default string table.

Parameters
resId: @StringRes Int

Resource id for the string

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.

Parameters
resId: @StringRes Int

Resource id for the format string

formatArgs: Array<Any!>?

The format arguments that will be used for substitution.

getTag

Added in 1.1.0
fun getTag(): String?

Get the tag name of the fragment, if specified.

getTargetFragment

Added in 1.1.0
Deprecated in 1.3.0
fun getTargetFragment(): Fragment?

Return the target fragment set by setTargetFragment.

getTargetRequestCode

Added in 1.1.0
Deprecated in 1.3.0
fun getTargetRequestCode(): Int

Return the target request code set by setTargetFragment.

getText

Added in 1.1.0
fun getText(resId: @StringRes Int): CharSequence

Return a localized, styled CharSequence from the application's package's default string table.

Parameters
resId: @StringRes Int

Resource id for the CharSequence text

getUserVisibleHint

Added in 1.1.0
Deprecated in 1.1.0
fun getUserVisibleHint(): Boolean
Returns
Boolean

The current value of the user-visible hint on this fragment.

getView

Added in 1.1.0
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

Added in 1.1.0
@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:

  1. created after onViewStateRestored
  2. started after onStart
  3. resumed after onResume
  4. paused before onPause
  5. stopped before onStop
  6. destroyed before onDestroyView
The first method where it is safe to access the view lifecycle is 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 LifecycleOwner that represents the Fragment's View lifecycle.

getViewLifecycleOwnerLiveData

Added in 1.1.0
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 getViewLifecycleOwner.

getViewModelStore

Added in 1.1.0
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 ViewModelStore

Throws
java.lang.IllegalStateException

if called before the Fragment is attached i.e., before onAttach().

hashCode

Added in 1.1.0
fun hashCode(): Int

Subclasses can not override hashCode().

instantiate

Added in 1.1.0
Deprecated in 1.1.0
java-static fun instantiate(context: Context, fname: String): Fragment

Like instantiate but with a null argument Bundle.

instantiate

Added in 1.1.0
Deprecated in 1.1.0
java-static fun instantiate(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 getArguments. May be null.

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

Added in 1.1.0
fun isAdded(): Boolean

Return true if the fragment is currently added to its activity.

isDetached

Added in 1.1.0
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

Added in 1.1.0
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

Added in 1.1.0
fun isInLayout(): Boolean

Return true if the layout is included as part of an activity view hierarchy via the tag. This will always be true when fragments are created through the 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

Added in 1.1.0
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

Added in 1.1.0
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

Added in 1.1.0
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

Added in 1.1.0
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

Added in 1.1.0
Deprecated in 1.3.0
@MainThread
@CallSuper
fun onActivityCreated(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.

onActivityResult

Added in 1.1.0
Deprecated in 1.3.0
fun onActivityResult(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").

onAttach

Added in 1.1.0
Deprecated in 1.1.0
@MainThread
@CallSuper
fun onAttach(activity: Activity): Unit

Called when a fragment is first attached to its activity. onCreate will be called after this.

onAttach

Added in 1.1.0
@MainThread
@CallSuper
fun onAttach(context: Context): Unit

Called when a fragment is first attached to its context. onCreate will be called after this.

onAttachFragment

Added in 1.1.0
Deprecated in 1.3.0
@MainThread
fun onAttachFragment(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

Added in 1.1.0
@CallSuper
fun onConfigurationChanged(newConfig: Configuration): Unit

onContextItemSelected

Added in 1.1.0
@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

Added in 1.1.0
@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

Added in 1.1.0
@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 setTransition or 0 if not set.

enter: Boolean

true when the fragment is added/attached/shown or false when the fragment is removed/detached/hidden.

nextAnim: Int

The resource set in setCustomAnimations, setCustomAnimations, or 0 if neither was called. The value will depend on the current operation.

onCreateAnimator

Added in 1.1.0
@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 setTransition or 0 if not set.

enter: Boolean

true when the fragment is added/attached/shown or false when the fragment is removed/detached/hidden.

nextAnim: Int

The resource set in setCustomAnimations, setCustomAnimations, or 0 if neither was called. The value will depend on the current operation.

onCreateContextMenu

Added in 1.1.0
@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.

onCreateOptionsMenu

Added in 1.1.0
Deprecated in 1.5.0
@MainThread
fun onCreateOptionsMenu(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

Added in 1.1.0
@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

Added in 1.1.0
@MainThread
@CallSuper
fun onDestroy(): Unit

Called when the fragment is no longer in use. This is called after onStop and before onDetach.

onDestroyOptionsMenu

Added in 1.1.0
Deprecated in 1.5.0
@MainThread
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 was not called).

onDestroyView

Added in 1.1.0
@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

Added in 1.1.0
@MainThread
@CallSuper
fun onDetach(): Unit

Called when the fragment is no longer attached to its activity. This is called after onDestroy.

onGetLayoutInflater

Added in 1.1.0
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

Added in 1.1.0
@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.

onInflate

Added in 1.1.0
Deprecated in 1.1.0
@UiThread
@CallSuper
fun onInflate(
    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

Added in 1.1.0
@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.

onLowMemory

Added in 1.1.0
@MainThread
@CallSuper
fun onLowMemory(): Unit

onMultiWindowModeChanged

Added in 1.1.0
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.

onOptionsItemSelected

Added in 1.1.0
Deprecated in 1.5.0
@MainThread
fun onOptionsItemSelected(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.

onOptionsMenuClosed

Added in 1.1.0
Deprecated in 1.5.0
@MainThread
fun onOptionsMenuClosed(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

Added in 1.1.0
@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

Added in 1.1.0
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.

onPrepareOptionsMenu

Added in 1.1.0
Deprecated in 1.5.0
@MainThread
fun onPrepareOptionsMenu(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().

onPrimaryNavigationFragmentChanged

Added in 1.1.0
@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 parent fragment is set as the primary navigation fragment via setPrimaryNavigationFragment.

onRequestPermissionsResult

Added in 1.1.0
Deprecated in 1.3.0
fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<String!>,
    grantResults: IntArray
): 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 requestPermissions.

permissions: Array<String!>

The requested permissions. Never null.

grantResults: IntArray

The grant results for the corresponding permissions which is either PERMISSION_GRANTED or PERMISSION_DENIED. Never null.

onResume

Added in 1.1.0
@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

Added in 1.1.0
@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

Added in 1.1.0
@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

Added in 1.1.0
@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

Added in 1.1.0
@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 onCreateView.

savedInstanceState: Bundle?

If non-null, this fragment is being re-constructed from a previous saved state as given here.

onViewStateRestored

Added in 1.1.0
@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.

postponeEnterTransition

Added in 1.1.0
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

Added in 1.1.0
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.

Parameters
duration: Long

The length of the delay in timeUnit units

timeUnit: TimeUnit

The units of time for duration

registerForActivityResult

Added in 1.3.0
@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

Added in 1.3.0
@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 Intents

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

Added in 1.1.0
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.

requestPermissions

Added in 1.1.0
Deprecated in 1.3.0
fun requestPermissions(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 onRequestPermissionsResult. Must be between 0 and 65535 to be considered valid. If given requestCode is greater than 65535, an IllegalArgumentException would be thrown.

requireActivity

Added in 1.1.0
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

Added in 1.1.0
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

Added in 1.1.0
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

requireFragmentManager

Added in 1.1.0
Deprecated in 1.2.0
fun requireFragmentManager(): 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.

requireHost

Added in 1.1.0
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

Added in 1.1.0
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.

requireView

Added in 1.1.0
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 onCreateView.

See also
getView

setAllowEnterTransitionOverlap

Added in 1.1.0
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

Added in 1.1.0
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

Added in 1.1.0
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

Added in 1.1.0
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

Added in 1.1.0
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. transition must be an android.transition.Transition or androidx.transition.Transition.

setExitSharedElementCallback

Added in 1.1.0
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

Added in 1.1.0
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. transitionmust be an android.transition.Transition or androidx.transition.Transition.

setHasOptionsMenu

Added in 1.1.0
Deprecated in 1.5.0
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

Added in 1.1.0
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

Added in 1.1.0
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

Added in 1.1.0
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. transitionmust be an android.transition.Transition or androidx.transition.Transition.

setRetainInstance

Added in 1.1.0
Deprecated in 1.3.0
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 (but onDetach still will be, because the fragment is being detached from its current activity).
  • onCreate will not be called since the fragment is not being re-created.
  • onAttach and onActivityCreatedwill still be called.
Parameters
retain: Boolean

true to retain this fragment instance across configuration changes, false otherwise.

setReturnTransition

Added in 1.1.0
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. transition must be an android.transition.Transition or androidx.transition.Transition.

setSharedElementEnterTransition

Added in 1.1.0
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. transition must be an android.transition.Transition or androidx.transition.Transition.

setSharedElementReturnTransition

Added in 1.1.0
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. transition must be an android.transition.Transition or androidx.transition.Transition.

setTargetFragment

Added in 1.1.0
Deprecated in 1.3.0
fun setTargetFragment(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 onActivityResult.

setUserVisibleHint

Added in 1.1.0
Deprecated in 1.1.0
fun setUserVisibleHint(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

Added in 1.1.0
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

Added in 1.1.0
fun startActivity(intent: Intent): Unit

Call startActivity from the fragment's containing Activity.

startActivity

Added in 1.1.0
fun startActivity(intent: Intent, options: Bundle?): Unit

Call startActivity from the fragment's containing Activity.

startActivityForResult

Added in 1.1.0
Deprecated in 1.3.0
fun startActivityForResult(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 onActivityResult when the activity exits. Must be between 0 and 65535 to be considered valid. If given requestCode is greater than 65535, an IllegalArgumentException would be thrown.

startActivityForResult

Added in 1.1.0
Deprecated in 1.3.0
fun startActivityForResult(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 onActivityResult when the activity exits. Must be between 0 and 65535 to be considered valid. If given requestCode is greater than 65535, an IllegalArgumentException would be thrown.

options: Bundle?

Additional options for how the Activity should be started. See startActivity for more details. This value may be null.

startIntentSenderForResult

Added in 1.1.0
Deprecated in 1.3.0
fun startIntentSenderForResult(
    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 onActivityResult when the activity exits. Must be between 0 and 65535 to be considered valid. If given requestCode is greater than 65535, an IllegalArgumentException would be thrown.

fillInIntent: Intent?

If non-null, this will be provided as the intent parameter to sendIntent. This value may be null.

flagsMask: Int

Intent flags in the original IntentSender that you would like to change.

flagsValues: Int

Desired values for any bits set in flagsMask.

extraFlags: Int

Always set to 0.

options: Bundle?

Additional options for how the Activity should be started. See startActivity for more details. This value may be null.

startPostponedEnterTransition

Added in 1.1.0
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.

toString

fun toString(): String

unregisterForContextMenu

Added in 1.1.0
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.

Extension functions

authenticateWithClass2Biometrics

suspend fun Fragment.authenticateWithClass2Biometrics(
    title: CharSequence,
    negativeButtonText: CharSequence,
    subtitle: CharSequence? = null,
    description: CharSequence? = null,
    confirmationRequired: Boolean = true
): BiometricPrompt.AuthenticationResult

Prompts the user to authenticate with a Class 2 biometric (e.g. fingerprint, face, or iris).

Note that Class 3 biometrics are guaranteed to meet the requirements for Class 2 and thus will also be accepted.

Parameters
title: CharSequence

The title to be displayed on the prompt.

negativeButtonText: CharSequence

The label for the negative button on the prompt.

subtitle: CharSequence? = null

An optional subtitle to be displayed on the prompt.

description: CharSequence? = null

An optional description to be displayed on the prompt.

confirmationRequired: Boolean = true

Whether user confirmation should be required for passive biometrics.

Returns
BiometricPrompt.AuthenticationResult

AuthenticationResult for a successful authentication.

Throws
androidx.biometric.auth.AuthPromptErrorException

when an unrecoverable error has been encountered and authentication has stopped.

androidx.biometric.auth.AuthPromptFailureException

when an authentication attempt by the user has been rejected.

startClass2BiometricAuthentication

fun Fragment.startClass2BiometricAuthentication(
    title: CharSequence,
    negativeButtonText: CharSequence,
    subtitle: CharSequence? = null,
    description: CharSequence? = null,
    confirmationRequired: Boolean = true,
    executor: Executor? = null,
    callback: AuthPromptCallback
): AuthPrompt

Prompts the user to authenticate with a Class 2 biometric (e.g. fingerprint, face, or iris).

Note that Class 3 biometrics are guaranteed to meet the requirements for Class 2 and thus will also be accepted.

Parameters
title: CharSequence

The title to be displayed on the prompt.

negativeButtonText: CharSequence

The label for the negative button on the prompt.

subtitle: CharSequence? = null

An optional subtitle to be displayed on the prompt.

description: CharSequence? = null

An optional description to be displayed on the prompt.

confirmationRequired: Boolean = true

Whether user confirmation should be required for passive biometrics.

executor: Executor? = null

An executor for callback methods. If null, these will run on the main thread.

callback: AuthPromptCallback

The object that will receive and process authentication events.

Returns
AuthPrompt

An AuthPrompt handle to the shown prompt.

authenticateWithClass2BiometricsOrCredentials

suspend fun Fragment.authenticateWithClass2BiometricsOrCredentials(
    title: CharSequence,
    subtitle: CharSequence? = null,
    description: CharSequence? = null,
    confirmationRequired: Boolean = true
): BiometricPrompt.AuthenticationResult

Prompts the user to authenticate with a Class 2 biometric (e.g. fingerprint, face, or iris) or the screen lock credential (i.e. PIN, pattern, or password) for the device.

Note that Class 3 biometrics are guaranteed to meet the requirements for Class 2 and thus will also be accepted.

Parameters
title: CharSequence

The title to be displayed on the prompt.

subtitle: CharSequence? = null

An optional subtitle to be displayed on the prompt.

description: CharSequence? = null

An optional description to be displayed on the prompt.

confirmationRequired: Boolean = true

Whether user confirmation should be required for passive biometrics.

Returns
BiometricPrompt.AuthenticationResult

An AuthPrompt handle to the shown prompt.

Throws
androidx.biometric.auth.AuthPromptErrorException

when an unrecoverable error has been encountered and authentication has stopped.

androidx.biometric.auth.AuthPromptFailureException

when an authentication attempt by the user has been rejected.

startClass2BiometricOrCredentialAuthentication

fun Fragment.startClass2BiometricOrCredentialAuthentication(
    title: CharSequence,
    subtitle: CharSequence? = null,
    description: CharSequence? = null,
    confirmationRequired: Boolean = true,
    executor: Executor? = null,
    callback: AuthPromptCallback
): AuthPrompt

Prompts the user to authenticate with a Class 2 biometric (e.g. fingerprint, face, or iris) or the screen lock credential (i.e. PIN, pattern, or password) for the device.

Note that Class 3 biometrics are guaranteed to meet the requirements for Class 2 and thus will also be accepted.

Parameters
title: CharSequence

The title to be displayed on the prompt.

subtitle: CharSequence? = null

An optional subtitle to be displayed on the prompt.

description: CharSequence? = null

An optional description to be displayed on the prompt.

confirmationRequired: Boolean = true

Whether user confirmation should be required for passive biometrics.

executor: Executor? = null

An executor for callback methods. If null, these will run on the main thread.

callback: AuthPromptCallback

The object that will receive and process authentication events.

Returns
AuthPrompt

An AuthPrompt handle to the shown prompt.

authenticateWithClass3Biometrics

suspend fun Fragment.authenticateWithClass3Biometrics(
    crypto: BiometricPrompt.CryptoObject?,
    title: CharSequence,
    negativeButtonText: CharSequence,
    subtitle: CharSequence? = null,
    description: CharSequence? = null,
    confirmationRequired: Boolean = true
): BiometricPrompt.AuthenticationResult

Prompts the user to authenticate with a Class 3 biometric (e.g. fingerprint, face, or iris).

Parameters
crypto: BiometricPrompt.CryptoObject?

A cryptographic object to be associated with this authentication.

title: CharSequence

The title to be displayed on the prompt.

negativeButtonText: CharSequence

The label for the negative button on the prompt.

subtitle: CharSequence? = null

An optional subtitle to be displayed on the prompt.

description: CharSequence? = null

An optional description to be displayed on the prompt.

confirmationRequired: Boolean = true

Whether user confirmation should be required for passive biometrics.

Returns
BiometricPrompt.AuthenticationResult

AuthenticationResult for a successful authentication.

Throws
androidx.biometric.auth.AuthPromptErrorException

when an unrecoverable error has been encountered and authentication has stopped.

androidx.biometric.auth.AuthPromptFailureException

when an authentication attempt by the user has been rejected.

authenticateWithClass3Biometrics

fun Fragment.authenticateWithClass3Biometrics(
    crypto: BiometricPrompt.CryptoObject?,
    title: CharSequence,
    negativeButtonText: CharSequence,
    subtitle: CharSequence? = null,
    description: CharSequence? = null,
    confirmationRequired: Boolean = true,
    executor: Executor? = null,
    callback: AuthPromptCallback
): AuthPrompt

Prompts the user to authenticate with a Class 3 biometric (e.g. fingerprint, face, or iris).

Parameters
crypto: BiometricPrompt.CryptoObject?

A cryptographic object to be associated with this authentication.

title: CharSequence

The title to be displayed on the prompt.

negativeButtonText: CharSequence

The label for the negative button on the prompt.

subtitle: CharSequence? = null

An optional subtitle to be displayed on the prompt.

description: CharSequence? = null

An optional description to be displayed on the prompt.

confirmationRequired: Boolean = true

Whether user confirmation should be required for passive biometrics.

executor: Executor? = null

An executor for callback methods. If null, these will run on the main thread.

callback: AuthPromptCallback

The object that will receive and process authentication events.

Returns
AuthPrompt

An AuthPrompt handle to the shown prompt.

authenticateWithClass3BiometricsOrCredentials

@RequiresApi(value = 30)
suspend fun Fragment.authenticateWithClass3BiometricsOrCredentials(
    crypto: BiometricPrompt.CryptoObject?,
    title: CharSequence,
    subtitle: CharSequence? = null,
    description: CharSequence? = null,
    confirmationRequired: Boolean = true
): BiometricPrompt.AuthenticationResult

Prompts the user to authenticate with a Class 3 biometric (e.g. fingerprint, face, or iris) or the screen lock credential (i.e. PIN, pattern, or password) for the device.

Parameters
crypto: BiometricPrompt.CryptoObject?

A cryptographic object to be associated with this authentication.

title: CharSequence

The title to be displayed on the prompt.

subtitle: CharSequence? = null

An optional subtitle to be displayed on the prompt.

description: CharSequence? = null

An optional description to be displayed on the prompt.

confirmationRequired: Boolean = true

Whether user confirmation should be required for passive biometrics.

Returns
BiometricPrompt.AuthenticationResult

AuthenticationResult for a successful authentication.

Throws
androidx.biometric.auth.AuthPromptErrorException

when an unrecoverable error has been encountered and authentication has stopped.

androidx.biometric.auth.AuthPromptFailureException

when an authentication attempt by the user has been rejected.

startClass3BiometricOrCredentialAuthentication

@RequiresApi(value = 30)
fun Fragment.startClass3BiometricOrCredentialAuthentication(
    crypto: BiometricPrompt.CryptoObject?,
    title: CharSequence,
    subtitle: CharSequence? = null,
    description: CharSequence? = null,
    confirmationRequired: Boolean = true,
    executor: Executor? = null,
    callback: AuthPromptCallback
): AuthPrompt

Prompts the user to authenticate with a Class 3 biometric (e.g. fingerprint, face, or iris) or the screen lock credential (i.e. PIN, pattern, or password) for the device.

Parameters
crypto: BiometricPrompt.CryptoObject?

A cryptographic object to be associated with this authentication.

title: CharSequence

The title to be displayed on the prompt.

subtitle: CharSequence? = null

An optional subtitle to be displayed on the prompt.

description: CharSequence? = null

An optional description to be displayed on the prompt.

confirmationRequired: Boolean = true

Whether user confirmation should be required for passive biometrics.

executor: Executor? = null

An executor for callback methods. If null, these will run on the main thread.

callback: AuthPromptCallback

The object that will receive and process authentication events.

Returns
AuthPrompt

An AuthPrompt handle to the shown prompt.

authenticateWithCredentials

@RequiresApi(value = 30)
suspend fun Fragment.authenticateWithCredentials(
    crypto: BiometricPrompt.CryptoObject?,
    title: CharSequence,
    description: CharSequence? = null
): BiometricPrompt.AuthenticationResult

Prompts the user to authenticate with the screen lock credential (i.e. PIN, pattern, or password) for the device.

Parameters
crypto: BiometricPrompt.CryptoObject?

A cryptographic object to be associated with this authentication.

title: CharSequence

The title to be displayed on the prompt.

description: CharSequence? = null

An optional description to be displayed on the prompt.

Returns
BiometricPrompt.AuthenticationResult

AuthenticationResult for a successful authentication.

Throws
androidx.biometric.auth.AuthPromptErrorException

when an unrecoverable error has been encountered and authentication has stopped.

androidx.biometric.auth.AuthPromptFailureException

when an authentication attempt by the user has been rejected.

startCredentialAuthentication

@RequiresApi(value = 30)
fun Fragment.startCredentialAuthentication(
    crypto: BiometricPrompt.CryptoObject?,
    title: CharSequence,
    description: CharSequence? = null,
    executor: Executor? = null,
    callback: AuthPromptCallback
): AuthPrompt

Prompts the user to authenticate with the screen lock credential (i.e. PIN, pattern, or password) for the device.

Parameters
crypto: BiometricPrompt.CryptoObject?

A cryptographic object to be associated with this authentication.

title: CharSequence

The title to be displayed on the prompt.

description: CharSequence? = null

An optional description to be displayed on the prompt.

executor: Executor? = null

An executor for callback methods. If null, these will run on the main thread.

callback: AuthPromptCallback

The object that will receive and process authentication events.

Returns
AuthPrompt

An AuthPrompt handle to the shown prompt.

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

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

fun Fragment.content(content: @Composable () -> Unit): <Error class: unknown class>

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
}
}
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

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.

Parameters
requestKey: String

key used to identify the result

result: Bundle

the result to be passed to another 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.

Parameters
requestKey: String

requestKey used to store the result

listener: (requestKey: String, bundle: Bundle) -> Unit

listener for result changes.

@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.

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.

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 default factory.

This method also takes an CreationExtras produces that provides default extras to the created view model.

@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.

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 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 NavController back stack

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 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 NavController back stack

noinline creationCallback: (VMF) -> VM

callback that takes an @AssistedFactory-annotated factory and creates a HiltViewModel using @AssistedInject-annotated constructor.

@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 NavController back stack

noinline extrasProducer: (() -> CreationExtras)? = null

lambda that will be called during initialization to return CreationExtras. If none is provided, this will use the extras from the NavBackStackEntry referenced by the navGraphId.

noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null

lambda that will be called during initialization to return ViewModelProvider.Factory. If none is provided, this will use the factory from the NavBackStackEntry referenced by the navGraphId.

@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

NavDestination.route of a NavGraph that exists on the NavController back stack. If a NavDestination with the given route does not exist on the back stack, an IllegalArgumentException will be thrown.

noinline extrasProducer: (() -> CreationExtras)? = null

lambda that will be called during initialization to return CreationExtras. If none is provided, this will use the extras from the NavBackStackEntry referenced by the navGraphRoute.

noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null

lambda that will be called during initialization to return ViewModelProvider.Factory. If none is provided, this will use the factory from the NavBackStackEntry referenced by the navGraphRoute.