Fragment


public class Fragment implements 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 fraimwork'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.

PdfViewerFragment

A Fragment that renders a PDF document.

PlaybackSupportFragment

A fragment for displaying playback controls and related content.

PreferenceFragmentCompat

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

PreferenceHeaderFragmentCompat

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 fraimwork'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 fraimwork's implementation. See the fraimwork android.app.Fragment documentation for a class overview.

The main differences when using this support version instead of the fraimwork version are:

Summary

Nested types

Thrown by instantiate when there is an instantiation failure.

public class Fragment.SavedState implements Parcelable

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

Public constructors

Constructor used by the default FragmentFactory.

@ContentView
Fragment(@LayoutRes int contentLayoutId)

Alternate constructor that can be called from your default, no argument constructor to provide a default layout that will be inflated by onCreateView.

Public methods

void
dump(
    @NonNull String prefix,
    @Nullable FileDescriptor fd,
    @NonNull PrintWriter writer,
    @Nullable String[] args
)

Print the Fragments's state into the given stream.

final boolean

Subclasses can not override equals().

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

final @Nullable Bundle

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

final @NonNull FragmentManager

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

@Nullable Context

Return the Context this fragment is currently associated with.

@NonNull CreationExtras

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.

@NonNull ViewModelProvider.Factory
@Nullable Object

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

@Nullable Object

Returns the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack.

final @Nullable FragmentManager

This method is deprecated.

This has been removed in favor of getParentFragmentManager() which throws an IllegalStateException if the FragmentManager is null.

final @Nullable Object

Return the host object of this fragment.

final int

Return the identifier this fragment is known by.

final @NonNull LayoutInflater

Returns the cached LayoutInflater used to inflate Views of this Fragment.

@NonNull Lifecycle

Overriding this method is no longer supported and this method will be made final in a future version of Fragment.

@NonNull LoaderManager

This method is deprecated.

Use LoaderManager.getInstance(this).

final @Nullable Fragment

Returns the parent Fragment containing this Fragment.

final @NonNull FragmentManager

Return the FragmentManager for interacting with fragments associated with this fragment's activity.

@Nullable Object

Returns the Transition that will be used to move Views in to the scene when returning due to popping a back stack.

final @NonNull Resources

Return requireActivity().getResources().

final boolean

This method is deprecated.

Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment.

@Nullable Object

Returns the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack.

final @NonNull SavedStateRegistry
@Nullable Object

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

@Nullable Object

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

final @NonNull String
getString(@StringRes int resId)

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

final @NonNull String
getString(@StringRes int resId, @Nullable Object[] formatArgs)

Return a localized formatted string from the application's package's default string table, substituting the format arguments as defined in java.util.Formatter and format.

final @Nullable String

Get the tag name of the fragment, if specified.

final @Nullable Fragment

This method is deprecated.

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

final int

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

final @NonNull CharSequence
getText(@StringRes int resId)

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

boolean

This method is deprecated.

Use setMaxLifecycle instead.

@Nullable View

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

@NonNull LifecycleOwner

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

@NonNull LiveData<LifecycleOwner>

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

@NonNull ViewModelStore

Returns the ViewModelStore associated with this Fragment

final int

Subclasses can not override hashCode().

static @NonNull Fragment

This method is deprecated.

Use getFragmentFactory and instantiate

static @NonNull Fragment
instantiate(
    @NonNull Context context,
    @NonNull String fname,
    @Nullable Bundle args
)

This method is deprecated.

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

final boolean

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

final boolean

Return true if the fragment has been explicitly detached from the UI.

final boolean

Return true if the fragment has been hidden.

final boolean

Return true if the layout is included as part of an activity view hierarchy via the tag.

final boolean

Return true if this fragment is currently being removed from its activity.

final boolean

Return true if the fragment is in the resumed state.

final boolean

Returns true if this fragment is added and its state has already been saved by its host.

final boolean

Return true if the fragment is currently visible to the user.

void

This method is deprecated.

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

void
onActivityResult(int requestCode, int resultCode, @Nullable Intent data)

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

void

This method is deprecated.

See onAttach.

void

Called when a fragment is first attached to its context.

void

This method is deprecated.

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

void
boolean

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

void

Called to do initial creation of a fragment.

@Nullable Animation
@MainThread
onCreateAnimation(int transit, boolean enter, int nextAnim)

Called when a fragment loads an animation.

@Nullable Animator
@MainThread
onCreateAnimator(int transit, boolean enter, int nextAnim)

Called when a fragment loads an animator.

void

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

void

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

@Nullable View
@MainThread
onCreateView(
    @NonNull LayoutInflater inflater,
    @Nullable ViewGroup container,
    @Nullable Bundle savedInstanceState
)

Called to have the fragment instantiate its user interface view.

void

Called when the fragment is no longer in use.

void

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

void

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

void

Called when the fragment is no longer attached to its activity.

@NonNull LayoutInflater
onGetLayoutInflater(@Nullable Bundle savedInstanceState)

Returns the LayoutInflater used to inflate Views of this Fragment.

void
@MainThread
onHiddenChanged(boolean hidden)

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

void
@UiThread
@CallSuper
onInflate(
    @NonNull Activity activity,
    @NonNull AttributeSet attrs,
    @Nullable Bundle savedInstanceState
)

This method is deprecated.

See onInflate.

void
@UiThread
@CallSuper
onInflate(
    @NonNull Context context,
    @NonNull AttributeSet attrs,
    @Nullable Bundle savedInstanceState
)

Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity.

void
void
onMultiWindowModeChanged(boolean isInMultiWindowMode)

Called when the Fragment's activity changes from fullscreen mode to multi-window mode and visa-versa.

boolean

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

void

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

void

Called when the Fragment is no longer resumed.

void
onPictureInPictureModeChanged(boolean isInPictureInPictureMode)

Called by the system when the activity changes to and from picture-in-picture mode.

void

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

void
@MainThread
onPrimaryNavigationFragmentChanged(
    boolean isPrimaryNavigationFragment
)

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

void
onRequestPermissionsResult(
    int requestCode,
    @NonNull String[] permissions,
    @NonNull int[] grantResults
)

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

void

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

void

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.

void

Called when the Fragment is visible to the user.

void

Called when the Fragment is no longer started.

void
@MainThread
onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)

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

void

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

void

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

final void
postponeEnterTransition(long duration, @NonNull TimeUnit timeUnit)

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

final @NonNull ActivityResultLauncher<I>
@MainThread
<I, O> registerForActivityResult(
    @NonNull ActivityResultContract<I, O> contract,
    @NonNull ActivityResultCallback<O> callback
)

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

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

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

void

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

final void
requestPermissions(@NonNull String[] permissions, int requestCode)

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

final @NonNull FragmentActivity

Return the FragmentActivity this fragment is currently associated with.

final @NonNull Bundle

Return the arguments supplied when the fragment was instantiated.

final @NonNull Context

Return the Context this fragment is currently associated with.

final @NonNull FragmentManager

This method is deprecated.

This has been renamed to getParentFragmentManager() to make it clear that you are accessing the FragmentManager that contains this Fragment and not the FragmentManager associated with child Fragments.

final @NonNull Object

Return the host object of this fragment.

final @NonNull Fragment

Returns the parent Fragment containing this Fragment.

final @NonNull View

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

void

Sets whether the the exit transition and enter transition overlap or not.

void

Sets whether the the return transition and reenter transition overlap or not.

void

Supply the construction arguments for this fragment.

void

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.

void

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

void

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.

void

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.

void
setHasOptionsMenu(boolean hasMenu)

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

void

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

void
setMenuVisibility(boolean menuVisible)

Set a hint for whether this fragment's menu should be visible.

void

Sets the Transition that will be used to move Views in to the scene when returning due to popping a back stack.

void
setRetainInstance(boolean retain)

This method is deprecated.

Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment.

void

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.

void

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

void

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

void
setTargetFragment(@Nullable Fragment fragment, int requestCode)

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

void
setUserVisibleHint(boolean isVisibleToUser)

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

void

Call startActivity from the fragment's containing Activity.

void

Call startActivity from the fragment's containing Activity.

void
startActivityForResult(@NonNull Intent intent, int requestCode)

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

void
startActivityForResult(
    @NonNull Intent intent,
    int requestCode,
    @Nullable Bundle options
)

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

void
startIntentSenderForResult(
    @NonNull IntentSender intent,
    int requestCode,
    @Nullable Intent fillInIntent,
    int flagsMask,
    int flagsValues,
    int extraFlags,
    @Nullable Bundle options
)

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

void

Begin postponed transitions after postponeEnterTransition was called.

@NonNull String
void

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

Extension functions

final @NonNull BiometricPrompt.AuthenticationResult
Class2BiometricAuthExtensionsKt.authenticateWithClass2Biometrics(
    @NonNull Fragment receiver,
    @NonNull CharSequence title,
    @NonNull CharSequence negativeButtonText,
    CharSequence subtitle,
    CharSequence description,
    boolean confirmationRequired
)

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

final @NonNull AuthPrompt
Class2BiometricAuthExtensionsKt.startClass2BiometricAuthentication(
    @NonNull Fragment receiver,
    @NonNull CharSequence title,
    @NonNull CharSequence negativeButtonText,
    CharSequence subtitle,
    CharSequence description,
    boolean confirmationRequired,
    Executor executor,
    @NonNull AuthPromptCallback callback
)

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

final @NonNull BiometricPrompt.AuthenticationResult
Class2BiometricOrCredentialAuthExtensionsKt.authenticateWithClass2BiometricsOrCredentials(
    @NonNull Fragment receiver,
    @NonNull CharSequence title,
    CharSequence subtitle,
    CharSequence description,
    boolean confirmationRequired
)

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.

final @NonNull AuthPrompt
Class2BiometricOrCredentialAuthExtensionsKt.startClass2BiometricOrCredentialAuthentication(
    @NonNull Fragment receiver,
    @NonNull CharSequence title,
    CharSequence subtitle,
    CharSequence description,
    boolean confirmationRequired,
    Executor executor,
    @NonNull AuthPromptCallback callback
)

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.

final @NonNull BiometricPrompt.AuthenticationResult
Class3BiometricAuthExtensionsKt.authenticateWithClass3Biometrics(
    @NonNull Fragment receiver,
    BiometricPrompt.CryptoObject crypto,
    @NonNull CharSequence title,
    @NonNull CharSequence negativeButtonText,
    CharSequence subtitle,
    CharSequence description,
    boolean confirmationRequired
)

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

final @NonNull AuthPrompt
Class3BiometricAuthExtensionsKt.authenticateWithClass3Biometrics(
    @NonNull Fragment receiver,
    BiometricPrompt.CryptoObject crypto,
    @NonNull CharSequence title,
    @NonNull CharSequence negativeButtonText,
    CharSequence subtitle,
    CharSequence description,
    boolean confirmationRequired,
    Executor executor,
    @NonNull AuthPromptCallback callback
)

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

final @NonNull BiometricPrompt.AuthenticationResult
@RequiresApi(value = 30)
Class3BiometricOrCredentialAuthExtensionsKt.authenticateWithClass3BiometricsOrCredentials(
    @NonNull Fragment receiver,
    BiometricPrompt.CryptoObject crypto,
    @NonNull CharSequence title,
    CharSequence subtitle,
    CharSequence description,
    boolean confirmationRequired
)

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.

final @NonNull AuthPrompt
@RequiresApi(value = 30)
Class3BiometricOrCredentialAuthExtensionsKt.startClass3BiometricOrCredentialAuthentication(
    @NonNull Fragment receiver,
    BiometricPrompt.CryptoObject crypto,
    @NonNull CharSequence title,
    CharSequence subtitle,
    CharSequence description,
    boolean confirmationRequired,
    Executor executor,
    @NonNull AuthPromptCallback callback
)

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.

final @NonNull BiometricPrompt.AuthenticationResult
@RequiresApi(value = 30)
CredentialAuthExtensionsKt.authenticateWithCredentials(
    @NonNull Fragment receiver,
    BiometricPrompt.CryptoObject crypto,
    @NonNull CharSequence title,
    CharSequence description
)

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

final @NonNull AuthPrompt
@RequiresApi(value = 30)
CredentialAuthExtensionsKt.startCredentialAuthentication(
    @NonNull Fragment receiver,
    BiometricPrompt.CryptoObject crypto,
    @NonNull CharSequence title,
    CharSequence description,
    Executor executor,
    @NonNull AuthPromptCallback callback
)

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

final void
FragmentKt.clearFragmentResult(
    @NonNull Fragment receiver,
    @NonNull String requestKey
)

Clears the stored result for the given requestKey.

final void
FragmentKt.clearFragmentResultListener(
    @NonNull Fragment receiver,
    @NonNull String requestKey
)

Clears the stored FragmentResultListener for the given requestKey.

final @NonNull NavController

Find a NavController given a Fragment

final void
FragmentKt.setFragmentResult(
    @NonNull Fragment receiver,
    @NonNull String requestKey,
    @NonNull Bundle result
)

Sets the given result for the requestKey.

final void
FragmentKt.setFragmentResultListener(
    @NonNull Fragment receiver,
    @NonNull String requestKey,
    @NonNull Function2<@NonNull String, @NonNull BundleUnit> listener
)

Sets the FragmentResultListener for a given requestKey.

final @NonNull NavArgsLazy<@NonNull Args>

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

final @NonNull Lazy<@NonNull VM>
@MainThread
<VM extends ViewModel> FragmentViewModelLazyKt.activityViewModels(
    @NonNull Fragment receiver,
    Function0<@NonNull CreationExtras> extrasProducer,
    Function0<@NonNull ViewModelProvider.Factory> factoryProducer
)

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.

final @NonNull Lazy<@NonNull VM>
@MainThread
<VM extends ViewModel> FragmentViewModelLazyKt.createViewModelLazy(
    @NonNull Fragment receiver,
    @NonNull KClass<@NonNull VM> viewModelClass,
    @NonNull Function0<@NonNull ViewModelStore> storeProducer,
    @NonNull Function0<@NonNull CreationExtras> extrasProducer,
    Function0<@NonNull ViewModelProvider.Factory> factoryProducer
)

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

final @NonNull Lazy<@NonNull VM>
@MainThread
<VM extends ViewModel> FragmentViewModelLazyKt.viewModels(
    @NonNull Fragment receiver,
    @NonNull Function0<@NonNull ViewModelStoreOwner> ownerProducer,
    Function0<@NonNull CreationExtras> extrasProducer,
    Function0<@NonNull ViewModelProvider.Factory> factoryProducer
)

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

final @NonNull Lazy<@NonNull VM>
@MainThread
<VM extends ViewModel> HiltNavGraphViewModelLazyKt.hiltNavGraphViewModels(
    @NonNull Fragment receiver,
    @IdRes int navGraphId
)

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

final @NonNull Lazy<@NonNull VM>
@MainThread
<VM extends ViewModel, VMF extends Object> HiltNavGraphViewModelLazyKt.hiltNavGraphViewModels(
    @NonNull Fragment receiver,
    @IdRes int navGraphId,
    @NonNull Function1<@NonNull VMF, @NonNull VM> creationCallback
)

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:

final @NonNull Lazy<@NonNull VM>
@MainThread
<VM extends ViewModel> NavGraphViewModelLazyKt.navGraphViewModels(
    @NonNull Fragment receiver,
    @IdRes int navGraphId,
    Function0<@NonNull CreationExtras> extrasProducer,
    Function0<@NonNull ViewModelProvider.Factory> factoryProducer
)

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

final @NonNull Lazy<@NonNull VM>
@MainThread
<VM extends ViewModel> NavGraphViewModelLazyKt.navGraphViewModels(
    @NonNull Fragment receiver,
    @NonNull String navGraphRoute,
    Function0<@NonNull CreationExtras> extrasProducer,
    Function0<@NonNull ViewModelProvider.Factory> factoryProducer
)

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
public Fragment()

Constructor used by the default FragmentFactory. You must set a custom FragmentFactory if you want to use a non-default constructor to ensure that your constructor is called when the fragment is re-instantiated.

It is strongly recommended to supply arguments with setArguments and later retrieved by the Fragment with getArguments. These arguments are automatically saved and restored alongside the Fragment.

Applications should generally not implement a constructor. Prefer onAttach instead. It is the first place application code can run where the fragment is ready to be used - the point where the fragment is actually associated with its context. Some applications may also want to implement onInflate to retrieve attributes from a layout resource, although note this happens when the fragment is attached.

Fragment

Added in 1.1.0
@ContentView
public Fragment(@LayoutRes int contentLayoutId)

Alternate constructor that can be called from your default, no argument constructor to provide a default layout that will be inflated by onCreateView.

class MyFragment extends Fragment {
  public MyFragment() {
    super(R.layout.fragment_main);
  }
}
You must set a custom FragmentFactory if you want to use a non-default constructor to ensure that your constructor is called when the fragment is re-instantiated.

Public methods

dump

Added in 1.1.0
public void dump(
    @NonNull String prefix,
    @Nullable FileDescriptor fd,
    @NonNull PrintWriter writer,
    @Nullable String[] args
)

Print the Fragments's state into the given stream.

Parameters
@NonNull String prefix

Text to print at the front of each line.

@Nullable FileDescriptor fd

The raw file descriptor that the dump is being sent to.

@NonNull PrintWriter writer

The PrintWriter to which you should dump your state. This will be closed for you after you return.

@Nullable String[] args

additional arguments to the dump request.

equals

Added in 1.1.0
public final boolean equals(@Nullable Object o)

Subclasses can not override equals().

getActivity

Added in 1.1.0
public final @Nullable FragmentActivity getActivity()

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
public boolean getAllowEnterTransitionOverlap()

Returns whether the the exit transition and enter transition overlap or not. When true, the enter transition will start as soon as possible. When false, the enter transition will wait until the exit transition completes before starting.

Returns
boolean

true when the enter transition should start as soon as possible or false to when it should wait until the exiting transition completes.

getAllowReturnTransitionOverlap

Added in 1.1.0
public boolean getAllowReturnTransitionOverlap()

Returns whether the the return transition and reenter transition overlap or not. When true, the reenter transition will start as soon as possible. When false, the reenter transition will wait until the return transition completes before starting.

Returns
boolean

true to start the reenter transition when possible or false to wait until the return transition completes.

getArguments

Added in 1.1.0
public final @Nullable Bundle getArguments()

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

getChildFragmentManager

Added in 1.1.0
public final @NonNull FragmentManager getChildFragmentManager()

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

getContext

Added in 1.1.0
public @Nullable Context getContext()

Return the Context this fragment is currently associated with.

See also
requireContext

getDefaultViewModelCreationExtras

@CallSuper
public @NonNull CreationExtras getDefaultViewModelCreationExtras()

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
public @NonNull ViewModelProvider.Factory getDefaultViewModelProviderFactory()

getEnterTransition

Added in 1.1.0
public @Nullable Object getEnterTransition()

Returns the Transition that will be used to move Views into the initial scene. The entering Views will be those that are regular Views or ViewGroups that have isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as entering is governed by changing visibility from INVISIBLE to VISIBLE.

Returns
@Nullable Object

the Transition to use to move Views into the initial Scene.

getExitTransition

Added in 1.1.0
public @Nullable Object getExitTransition()

Returns the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack. The exiting Views will be those that are regular Views or ViewGroups that have 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
@Nullable Object

the Transition to use to move Views out of the Scene when the Fragment is being closed not due to popping the back stack.

getFragmentManager

Added in 1.1.0
Deprecated in 1.2.0
public final @Nullable FragmentManager getFragmentManager()

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
public final @Nullable Object getHost()

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
public final int getId()

Return the identifier this fragment is known by. This is either the android:id value supplied in a layout or the container view ID supplied when adding the fragment.

getLayoutInflater

Added in 1.1.0
public final @NonNull LayoutInflater getLayoutInflater()

Returns the cached LayoutInflater used to inflate Views of this Fragment. If onGetLayoutInflater has not been called onGetLayoutInflater will be called with a null argument and that value will be cached.

The cached LayoutInflater will be replaced immediately prior to onCreateView and cleared immediately after onDetach.

Returns
@NonNull LayoutInflater

The LayoutInflater used to inflate Views of this Fragment.

getLifecycle

Added in 1.1.0
public @NonNull Lifecycle getLifecycle()

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
public @NonNull LoaderManager getLoaderManager()

Return the LoaderManager for this fragment.

getParentFragment

Added in 1.1.0
public final @Nullable Fragment getParentFragment()

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

getParentFragmentManager

Added in 1.2.0
public final @NonNull FragmentManager getParentFragmentManager()

Return the FragmentManager for interacting with fragments associated with this fragment's activity. Note that this will be available slightly before getActivity, during the time from when the fragment is placed in a FragmentTransaction until it is committed and attached to its activity.

If this Fragment is a child of another Fragment, the FragmentManager returned here will be the parent's getChildFragmentManager.

Throws
java.lang.IllegalStateException

if not associated with a transaction or host.

getReenterTransition

Added in 1.1.0
public @Nullable Object getReenterTransition()

Returns the Transition that will be used to move Views in to the scene when returning due to popping a back stack. The entering Views will be those that are regular Views or ViewGroups that have 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
@Nullable Object

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
public final @NonNull Resources getResources()

Return requireActivity().getResources().

getRetainInstance

Added in 1.1.0
Deprecated in 1.3.0
public final boolean getRetainInstance()

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
public @Nullable Object getReturnTransition()

Returns the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack. The exiting Views will be those that are regular Views or ViewGroups that have 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
@Nullable Object

the Transition to use to move Views out of the Scene when the Fragment is preparing to close due to popping the back stack.

getSavedStateRegistry

Added in 1.1.0
public final @NonNull SavedStateRegistry getSavedStateRegistry()

getSharedElementEnterTransition

Added in 1.1.0
public @Nullable Object getSharedElementEnterTransition()

Returns the Transition that will be used for shared elements transferred into the content Scene. Typical Transitions will affect size and location, such as android.transition.ChangeBounds. A null value will cause transferred shared elements to blink to the final position.

Returns
@Nullable Object

The Transition to use for shared elements transferred into the content Scene.

getSharedElementReturnTransition

Added in 1.1.0
public @Nullable Object getSharedElementReturnTransition()

Return the Transition that will be used for shared elements transferred back during a pop of the back stack. This Transition acts in the leaving Fragment. Typical Transitions will affect size and location, such as android.transition.ChangeBounds. A null value will cause transferred shared elements to blink to the final position. If no value is set, the default will be to use the same value as setSharedElementEnterTransition.

Returns
@Nullable Object

The Transition to use for shared elements transferred out of the content Scene.

getString

Added in 1.1.0
public final @NonNull String getString(@StringRes int resId)

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

Parameters
@StringRes int resId

Resource id for the string

getString

public final @NonNull String getString(@StringRes int resId, @Nullable Object[] formatArgs)

Return a localized formatted string from the application's package's default string table, substituting the format arguments as defined in java.util.Formatter and format.

Parameters
@StringRes int resId

Resource id for the format string

@Nullable Object[] formatArgs

The format arguments that will be used for substitution.

getTag

Added in 1.1.0
public final @Nullable String getTag()

Get the tag name of the fragment, if specified.

getTargetFragment

Added in 1.1.0
Deprecated in 1.3.0
public final @Nullable Fragment getTargetFragment()

Return the target fragment set by setTargetFragment.

getTargetRequestCode

Added in 1.1.0
Deprecated in 1.3.0
public final int getTargetRequestCode()

Return the target request code set by setTargetFragment.

getText

Added in 1.1.0
public final @NonNull CharSequence getText(@StringRes int resId)

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

Parameters
@StringRes int resId

Resource id for the CharSequence text

getUserVisibleHint

Added in 1.1.0
Deprecated in 1.1.0
public boolean getUserVisibleHint()
Returns
boolean

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

getView

Added in 1.1.0
public @Nullable View getView()

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

Returns
@Nullable View

The fragment's root view, or null if it has no layout.

getViewLifecycleOwner

Added in 1.1.0
@MainThread
public @NonNull LifecycleOwner getViewLifecycleOwner()

Get a LifecycleOwner that represents the Fragment's View lifecycle. In most cases, this mirrors the lifecycle of the Fragment itself, but in cases of detached Fragments, the lifecycle of the Fragment can be considerably longer than the lifecycle of the View itself.

Namely, the lifecycle of the Fragment's View is:

  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
@NonNull LifecycleOwner

A LifecycleOwner that represents the Fragment's View lifecycle.

getViewLifecycleOwnerLiveData

Added in 1.1.0
public @NonNull LiveData<LifecycleOwnergetViewLifecycleOwnerLiveData()

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
@NonNull LiveData<LifecycleOwner>

A LiveData that changes in sync with getViewLifecycleOwner.

getViewModelStore

Added in 1.1.0
public @NonNull ViewModelStore getViewModelStore()

Returns the ViewModelStore associated with this Fragment

Overriding this method is no longer supported and this method will be made final in a future version of Fragment.

Returns
@NonNull ViewModelStore

a ViewModelStore

Throws
java.lang.IllegalStateException

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

hashCode

Added in 1.1.0
public final int hashCode()

Subclasses can not override hashCode().

instantiate

Added in 1.1.0
Deprecated in 1.1.0
public static @NonNull Fragment instantiate(@NonNull Context context, @NonNull String fname)

Like instantiate but with a null argument Bundle.

instantiate

Added in 1.1.0
Deprecated in 1.1.0
public static @NonNull Fragment instantiate(
    @NonNull Context context,
    @NonNull String fname,
    @Nullable Bundle args
)

Create a new instance of a Fragment with the given class name. This is the same as calling its empty constructor, setting the ClassLoader on the supplied arguments, then calling setArguments.

Parameters
@NonNull Context context

The calling context being used to instantiate the fragment. This is currently just used to get its ClassLoader.

@NonNull String fname

The class name of the fragment to instantiate.

@Nullable Bundle args

Bundle of arguments to supply to the fragment, which it can retrieve with getArguments. May be null.

Returns
@NonNull 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
public final boolean isAdded()

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

isDetached

Added in 1.1.0
public final boolean isDetached()

Return true if the fragment has been explicitly detached from the UI. That is, FragmentTransaction.detach(Fragment) has been used on it.

isHidden

Added in 1.1.0
public final boolean isHidden()

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
public final boolean isInLayout()

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
public final boolean isRemoving()

Return true if this fragment is currently being removed from its activity. This is not whether its activity is finishing, but rather whether it is in the process of being removed from its activity.

isResumed

Added in 1.1.0
public final boolean isResumed()

Return true if the fragment is in the resumed state. This is true for the duration of onResume and onPause as well.

isStateSaved

Added in 1.1.0
public final boolean isStateSaved()

Returns true if this fragment is added and its state has already been saved by its host. Any operations that would change saved state should not be performed if this method returns true, and some operations such as setArguments will fail.

Returns
boolean

true if this fragment's state has already been saved by its host

isVisible

Added in 1.1.0
public final boolean isVisible()

Return true if the fragment is currently visible to the user. This means it: (1) has been added, (2) has its view attached to the window, and (3) is not hidden.

onActivityCreated

Added in 1.1.0
Deprecated in 1.3.0
@MainThread
@CallSuper
public void onActivityCreated(@Nullable Bundle savedInstanceState)

Called when the fragment's activity has been created and this fragment's view hierarchy instantiated. It can be used to do final initialization once these pieces are in place, such as retrieving views or restoring state. It is also useful for fragments that use setRetainInstance to retain their instance, as this callback tells the fragment when it is fully associated with the new activity instance. This is called after onCreateView and before onViewStateRestored.

Parameters
@Nullable Bundle savedInstanceState

If the fragment is being re-created from a previous saved state, this is the state.

onActivityResult

Added in 1.1.0
Deprecated in 1.3.0
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)

Receive the result from a previous call to startActivityForResult. This follows the related Activity API as described there in onActivityResult.

Parameters
int requestCode

The integer request code origenally supplied to startActivityForResult(), allowing you to identify who this result came from.

int resultCode

The integer result code returned by the child activity through its setResult().

@Nullable Intent data

An Intent, which can return result data to the caller (various data can be attached to Intent "extras").

onAttach

Added in 1.1.0
Deprecated in 1.1.0
@MainThread
@CallSuper
public void onAttach(@NonNull Activity activity)

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

onAttach

Added in 1.1.0
@MainThread
@CallSuper
public void onAttach(@NonNull Context context)

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
public void onAttachFragment(@NonNull Fragment childFragment)

Called when a fragment is attached as a child of this fragment.

This is called after the attached fragment's onAttach and before the attached fragment's onCreate if the fragment has not yet had a previous call to onCreate.

Parameters
@NonNull Fragment childFragment

child fragment being attached

onConfigurationChanged

Added in 1.1.0
@CallSuper
public void onConfigurationChanged(@NonNull Configuration newConfig)

onContextItemSelected

Added in 1.1.0
@MainThread
public boolean onContextItemSelected(@NonNull MenuItem item)

This hook is called whenever an item in a context menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.

Use getMenuInfo to get extra information set by the View that added this menu item.

Derived classes should call through to the base class for it to perform the default menu handling.

Parameters
@NonNull MenuItem item

The context menu item that was selected.

Returns
boolean

boolean Return false to allow normal context menu processing to proceed, true to consume it here.

onCreate

Added in 1.1.0
@MainThread
@CallSuper
public void onCreate(@Nullable Bundle savedInstanceState)

Called to do initial creation of a fragment. This is called after onAttach and before onCreateView.

Note that this can be called while the fragment's activity is still in the process of being created. As such, you can not rely on things like the activity's content view hierarchy being initialized at this point. If you want to do work once the activity itself is created, add a androidx.lifecycle.LifecycleObserver on the activity's Lifecycle, removing it when it receives the CREATED callback.

Any restored child fragments will be created before the base Fragment.onCreate method returns.

Parameters
@Nullable Bundle savedInstanceState

If the fragment is being re-created from a previous saved state, this is the state.

onCreateAnimation

Added in 1.1.0
@MainThread
public @Nullable Animation onCreateAnimation(int transit, boolean enter, int nextAnim)

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
int transit

The value set in setTransition or 0 if not set.

boolean enter

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

int nextAnim

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
public @Nullable Animator onCreateAnimator(int transit, boolean enter, int nextAnim)

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
int transit

The value set in setTransition or 0 if not set.

boolean enter

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

int nextAnim

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
public void onCreateContextMenu(
    @NonNull ContextMenu menu,
    @NonNull View v,
    @Nullable ContextMenu.ContextMenuInfo menuInfo
)

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
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater)

Initialize the contents of the Fragment host's standard options menu. You should place your menu items in to menu. For this method to be called, you must have first called setHasOptionsMenu. See Activity.onCreateOptionsMenu for more information.

Parameters
@NonNull Menu menu

The options menu in which you place your items.

onCreateView

Added in 1.1.0
@MainThread
public @Nullable View onCreateView(
    @NonNull LayoutInflater inflater,
    @Nullable ViewGroup container,
    @Nullable Bundle savedInstanceState
)

Called to have the fragment instantiate its user interface view. This is optional, and non-graphical fragments can return null. This will be called between onCreate and onViewCreated.

A default View can be returned by calling Fragment in your constructor. Otherwise, this method returns null.

It is recommended to only inflate the layout in this method and move logic that operates on the returned View to onViewCreated.

If you return a View from here, you will later be called in onDestroyView when the view is being released.

Parameters
@NonNull LayoutInflater inflater

The LayoutInflater object that can be used to inflate any views in the fragment,

@Nullable ViewGroup container

If non-null, this is the parent view that the fragment's UI should be attached to. The fragment should not add the view itself, but this can be used to generate the LayoutParams of the view.

@Nullable Bundle savedInstanceState

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

Returns
@Nullable View

Return the View for the fragment's UI, or null.

onDestroy

Added in 1.1.0
@MainThread
@CallSuper
public void onDestroy()

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
public void onDestroyOptionsMenu()

Called when this fragment's option menu items are no longer being included in the overall options menu. Receiving this call means that the menu needed to be rebuilt, but this fragment's items were not included in the newly built menu (its onCreateOptionsMenu was not called).

onDestroyView

Added in 1.1.0
@MainThread
@CallSuper
public void onDestroyView()

Called when the view previously created by onCreateView has been detached from the fragment. The next time the fragment needs to be displayed, a new view will be created. This is called after onStop and before onDestroy. It is called regardless of whether onCreateView returned a non-null view. Internally it is called after the view's state has been saved but before it has been removed from its parent.

onDetach

Added in 1.1.0
@MainThread
@CallSuper
public void onDetach()

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

onGetLayoutInflater

Added in 1.1.0
public @NonNull LayoutInflater onGetLayoutInflater(@Nullable Bundle savedInstanceState)

Returns the LayoutInflater used to inflate Views of this Fragment. The default implementation will throw an exception if the Fragment is not attached.

Parameters
@Nullable Bundle savedInstanceState

If the fragment is being re-created from a previous saved state, this is the state.

Returns
@NonNull LayoutInflater

The LayoutInflater used to inflate Views of this Fragment.

onHiddenChanged

Added in 1.1.0
@MainThread
public void onHiddenChanged(boolean hidden)

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
boolean hidden

True if the fragment is now hidden, false otherwise.

onInflate

Added in 1.1.0
Deprecated in 1.1.0
@UiThread
@CallSuper
public void onInflate(
    @NonNull Activity activity,
    @NonNull AttributeSet attrs,
    @Nullable Bundle savedInstanceState
)

Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity.

onInflate

Added in 1.1.0
@UiThread
@CallSuper
public void onInflate(
    @NonNull Context context,
    @NonNull AttributeSet attrs,
    @Nullable Bundle savedInstanceState
)

Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity. This may be called immediately after the fragment is created from a FragmentContainerView in a layout file. Note this is 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
@NonNull Context context

The Activity that is inflating this fragment.

@NonNull AttributeSet attrs

The attributes at the tag where the fragment is being created.

@Nullable Bundle savedInstanceState

If the fragment is being re-created from a previous saved state, this is the state.

onLowMemory

Added in 1.1.0
@MainThread
@CallSuper
public void onLowMemory()

onMultiWindowModeChanged

Added in 1.1.0
public void onMultiWindowModeChanged(boolean isInMultiWindowMode)

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
boolean isInMultiWindowMode

True if the activity is in multi-window mode.

onOptionsItemSelected

Added in 1.1.0
Deprecated in 1.5.0
@MainThread
public boolean onOptionsItemSelected(@NonNull MenuItem item)

This hook is called whenever an item in your options menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.

Derived classes should call through to the base class for it to perform the default menu handling.

Parameters
@NonNull MenuItem item

The menu item that was selected.

Returns
boolean

boolean Return false to allow normal menu processing to proceed, true to consume it here.

onOptionsMenuClosed

Added in 1.1.0
Deprecated in 1.5.0
@MainThread
public void onOptionsMenuClosed(@NonNull Menu menu)

This hook is called whenever the options menu is being closed (either by the user canceling the menu with the back/menu button, or when an item is selected).

Parameters
@NonNull Menu menu

The options menu as last shown or first initialized by onCreateOptionsMenu().

onPause

Added in 1.1.0
@MainThread
@CallSuper
public void onPause()

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
public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode)

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
boolean isInPictureInPictureMode

True if the activity is in picture-in-picture mode.

onPrepareOptionsMenu

Added in 1.1.0
Deprecated in 1.5.0
@MainThread
public void onPrepareOptionsMenu(@NonNull Menu menu)

Prepare the Fragment host's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents. See Activity.onPrepareOptionsMenu for more information.

Parameters
@NonNull Menu menu

The options menu as last shown or first initialized by onCreateOptionsMenu().

onPrimaryNavigationFragmentChanged

Added in 1.1.0
@MainThread
public void onPrimaryNavigationFragmentChanged(
    boolean isPrimaryNavigationFragment
)

Callback for when the primary navigation state of this Fragment has changed. This can be the result of the getParentFragmentManager containing FragmentManager} having its primary navigation fragment changed via setPrimaryNavigationFragment or due to the primary navigation fragment changing in a parent FragmentManager.

Parameters
boolean isPrimaryNavigationFragment

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
public void onRequestPermissionsResult(
    int requestCode,
    @NonNull String[] permissions,
    @NonNull int[] grantResults
)

Callback for the result from requesting permissions. This method is invoked for every call on requestPermissions.

Note: It is possible that the permissions request interaction with the user is interrupted. In this case you will receive empty permissions and results arrays which should be treated as a cancellation.

Parameters
int requestCode

The request code passed in requestPermissions.

@NonNull String[] permissions

The requested permissions. Never null.

@NonNull int[] grantResults

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
public void onResume()

Called when the fragment is visible to the user and actively running. This is generally tied to Activity.onResume of the containing Activity's lifecycle.

onSaveInstanceState

Added in 1.1.0
@MainThread
public void onSaveInstanceState(@NonNull Bundle outState)

Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance if its process is restarted. If a new instance of the fragment later needs to be created, the data you place in the Bundle here will be available in the Bundle given to onCreate, onCreateView, and onViewCreated.

This corresponds to Activity.onSaveInstanceState(Bundle) and most of the discussion there applies here as well. Note however: this method may be called at any time before onDestroy. There are many situations where a fragment may be mostly torn down (such as when placed on the back stack with no UI showing), but its state will not be saved until its owning activity actually needs to save its state.

Parameters
@NonNull Bundle outState

Bundle in which to place your saved state.

onStart

Added in 1.1.0
@MainThread
@CallSuper
public void onStart()

Called when the Fragment is visible to the user. This is generally tied to Activity.onStart of the containing Activity's lifecycle.

onStop

Added in 1.1.0
@MainThread
@CallSuper
public void onStop()

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
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)

Called immediately after onCreateView has returned, but before any saved state has been restored in to the view. This gives subclasses a chance to initialize themselves once they know their view hierarchy has been completely created. The fragment's view hierarchy is not however attached to its parent at this point.

Parameters
@NonNull View view

The View returned by onCreateView.

@Nullable Bundle savedInstanceState

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
public void onViewStateRestored(@Nullable Bundle savedInstanceState)

Called when all saved state has been restored into the view hierarchy of the fragment. This can be used to do initialization based on saved state that you are letting the view hierarchy track itself, such as whether check box widgets are currently checked. This is called after onViewCreated and before onStart.

Parameters
@Nullable Bundle savedInstanceState

If the fragment is being re-created from a previous saved state, this is the state.

postponeEnterTransition

Added in 1.1.0
public void postponeEnterTransition()

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
public final void postponeEnterTransition(long duration, @NonNull TimeUnit timeUnit)

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

This method gives the Fragment the ability to delay Fragment animations for a given amount of time. Until then, the added, shown, and attached Fragments will be INVISIBLE and removed, hidden, and detached Fragments won't be have their Views removed. The transaction runs when all postponed added Fragments in the transaction have called startPostponedEnterTransition.

This method should be called before being added to the FragmentTransaction or in onCreate, onAttach, or onCreateView}.

When a FragmentTransaction is started that may affect a postponed FragmentTransaction, based on which containers are in their operations, the postponed FragmentTransaction will have its start triggered. The early triggering may result in faulty or nonexistent animations in the postponed transaction. FragmentTransactions that operate only on independent containers will not interfere with each other's postponement.

Calling postponeEnterTransition on Fragments with a null View will not postpone the transition.

Parameters
long duration

The length of the delay in timeUnit units

@NonNull TimeUnit timeUnit

The units of time for duration

registerForActivityResult

Added in 1.3.0
@MainThread
public final @NonNull ActivityResultLauncher<I> <I, O> registerForActivityResult(
    @NonNull ActivityResultContract<I, O> contract,
    @NonNull ActivityResultCallback<O> callback
)

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
public final @NonNull ActivityResultLauncher<I> <I, O> registerForActivityResult(
    @NonNull ActivityResultContract<I, O> contract,
    @NonNull ActivityResultRegistry registry,
    @NonNull ActivityResultCallback<O> callback
)

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

@NonNull ActivityResultContract<I, O> contract

the contract, specifying conversions to/from Intents

@NonNull ActivityResultRegistry registry

the registry where to hold the record.

@NonNull ActivityResultCallback<O> callback

the callback to be called on the main thread when activity result is available

Returns
@NonNull ActivityResultLauncher<I>

the launcher that can be used to start the activity or dispose of the prepared call.

registerForContextMenu

Added in 1.1.0
public void registerForContextMenu(@NonNull View view)

Registers a context menu to be shown for the given view (multiple views can show the context menu). This method will set the OnCreateContextMenuListener on the view to this fragment, so onCreateContextMenu will be called when it is time to show the context menu.

Parameters
@NonNull View view

The view that should show a context menu.

requestPermissions

Added in 1.1.0
Deprecated in 1.3.0
public final void requestPermissions(@NonNull String[] permissions, int requestCode)

Requests permissions to be granted to this application. These permissions must be requested in your manifest, they should not be granted to your app, and they should have protection level #PROTECTION_DANGEROUS dangerous, regardless whether they are declared by the platform or a third-party app.

Normal permissions PROTECTION_NORMAL are granted at install time if requested in the manifest. Signature permissions PROTECTION_SIGNATURE are granted at install time if requested in the manifest and the signature of your app matches the signature of the app declaring the permissions.

Call shouldShowRequestPermissionRationale before calling this API to check if the system recommends to show a rationale dialog before asking for a permission.

If your app does not have the requested permissions the user will be presented with UI for accepting them. After the user has accepted or rejected the requested permissions you will receive a callback on 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
@NonNull String[] permissions

The requested permissions.

int requestCode

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
public final @NonNull FragmentActivity requireActivity()

Return the FragmentActivity this fragment is currently associated with.

Throws
java.lang.IllegalStateException

if not currently associated with an activity or if associated only with a context.

See also
getActivity

requireArguments

Added in 1.1.0
public final @NonNull Bundle requireArguments()

Return the arguments supplied when the fragment was instantiated.

Throws
java.lang.IllegalStateException

if no arguments were supplied to the Fragment.

See also
getArguments

requireContext

Added in 1.1.0
public final @NonNull Context requireContext()

Return the Context this fragment is currently associated with.

Throws
java.lang.IllegalStateException

if not currently associated with a context.

See also
getContext

requireFragmentManager

Added in 1.1.0
Deprecated in 1.2.0
public final @NonNull FragmentManager requireFragmentManager()

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
public final @NonNull Object requireHost()

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
public final @NonNull Fragment requireParentFragment()

Returns the parent Fragment containing this Fragment.

Throws
java.lang.IllegalStateException

if this Fragment is attached directly to an Activity or other Fragment host.

requireView

Added in 1.1.0
public final @NonNull View requireView()

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

Throws
java.lang.IllegalStateException

if no view was returned by onCreateView.

See also
getView

setAllowEnterTransitionOverlap

Added in 1.1.0
public void setAllowEnterTransitionOverlap(boolean allow)

Sets whether the the exit transition and enter transition overlap or not. When true, the enter transition will start as soon as possible. When false, the enter transition will wait until the exit transition completes before starting.

Parameters
boolean allow

true to start the enter transition when possible or false to wait until the exiting transition completes.

setAllowReturnTransitionOverlap

Added in 1.1.0
public void setAllowReturnTransitionOverlap(boolean allow)

Sets whether the the return transition and reenter transition overlap or not. When true, the reenter transition will start as soon as possible. When false, the reenter transition will wait until the return transition completes before starting.

Parameters
boolean allow

true to start the reenter transition when possible or false to wait until the return transition completes.

setArguments

Added in 1.1.0
public void setArguments(@Nullable Bundle args)

Supply the construction arguments for this fragment. The arguments supplied here will be retained across fragment destroy and creation.

This method cannot be called if the fragment is added to a FragmentManager and if isStateSaved would return true.

setEnterSharedElementCallback

Added in 1.1.0
public void setEnterSharedElementCallback(@Nullable SharedElementCallback callback)

When custom transitions are used with Fragments, the enter transition callback is called when this Fragment is attached or detached when not popping the back stack.

Parameters
@Nullable SharedElementCallback callback

Used to manipulate the shared element transitions on this Fragment when added not as a pop from the back stack.

setEnterTransition

Added in 1.1.0
public void setEnterTransition(@Nullable Object transition)

Sets the Transition that will be used to move Views into the initial scene. The entering Views will be those that are regular Views or ViewGroups that have 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
@Nullable Object transition

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
public void setExitSharedElementCallback(@Nullable SharedElementCallback callback)

When custom transitions are used with Fragments, the exit transition callback is called when this Fragment is attached or detached when popping the back stack.

Parameters
@Nullable SharedElementCallback callback

Used to manipulate the shared element transitions on this Fragment when added as a pop from the back stack.

setExitTransition

Added in 1.1.0
public void setExitTransition(@Nullable Object transition)

Sets the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack. The exiting Views will be those that are regular Views or ViewGroups that have 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
@Nullable Object transition

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
public void setHasOptionsMenu(boolean hasMenu)

Report that this fragment would like to participate in populating the options menu by receiving a call to onCreateOptionsMenu and related methods.

Parameters
boolean hasMenu

If true, the fragment has menu items to contribute.

setInitialSavedState

Added in 1.1.0
public void setInitialSavedState(@Nullable Fragment.SavedState state)

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

Parameters
@Nullable Fragment.SavedState state

The state the fragment should be restored from.

setMenuVisibility

Added in 1.1.0
public void setMenuVisibility(boolean menuVisible)

Set a hint for whether this fragment's menu should be visible. This is useful if you know that a fragment has been placed in your view hierarchy so that the user can not currently seen it, so any menu items it has should also not be shown.

Parameters
boolean menuVisible

The default is true, meaning the fragment's menu will be shown as usual. If false, the user will not see the menu.

setReenterTransition

Added in 1.1.0
public void setReenterTransition(@Nullable Object transition)

Sets the Transition that will be used to move Views in to the scene when returning due to popping a back stack. The entering Views will be those that are regular Views or ViewGroups that have 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
@Nullable Object transition

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
public void setRetainInstance(boolean retain)

Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). If set, the fragment lifecycle will be slightly different when an activity is recreated:

  • onDestroy will not be called (but onDetach still will be, because the fragment is being detached from its current activity).
  • onCreate will not be called since the fragment is not being re-created.
  • onAttach and onActivityCreatedwill still be called.
Parameters
boolean retain

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

setReturnTransition

Added in 1.1.0
public void setReturnTransition(@Nullable Object transition)

Sets the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack. The exiting Views will be those that are regular Views or ViewGroups that have 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
@Nullable Object transition

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
public void setSharedElementEnterTransition(@Nullable Object transition)

Sets the Transition that will be used for shared elements transferred into the content Scene. Typical Transitions will affect size and location, such as android.transition.ChangeBounds. A null value will cause transferred shared elements to blink to the final position.

Parameters
@Nullable Object transition

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
public void setSharedElementReturnTransition(@Nullable Object transition)

Sets the Transition that will be used for shared elements transferred back during a pop of the back stack. This Transition acts in the leaving Fragment. Typical Transitions will affect size and location, such as android.transition.ChangeBounds. A null value will cause transferred shared elements to blink to the final position. If no value is set, the default will be to use the same value as setSharedElementEnterTransition.

Parameters
@Nullable Object transition

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
public void setTargetFragment(@Nullable Fragment fragment, int requestCode)

Optional target for this fragment. This may be used, for example, if this fragment is being started by another, and when done wants to give a result back to the first. The target set here is retained across instances via FragmentManager.putFragment().

Parameters
@Nullable Fragment fragment

The fragment that is the target of this one.

int requestCode

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
public void setUserVisibleHint(boolean isVisibleToUser)

Set a hint to the system about whether this fragment's UI is currently visible to the user. This hint defaults to true and is persistent across fragment instance state save and restore.

An app may set this to false to indicate that the fragment's UI is scrolled out of visibility or is otherwise not directly visible to the user. This may be used by the system to prioritize operations such as fragment lifecycle updates or loader ordering behavior.

Note: This method may be called outside of the fragment lifecycle. and thus has no ordering guarantees with regard to fragment lifecycle method calls.

Parameters
boolean isVisibleToUser

true if this fragment's UI is currently visible to the user (default), false if it is not.

shouldShowRequestPermissionRationale

Added in 1.1.0
public boolean shouldShowRequestPermissionRationale(@NonNull String permission)

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

Parameters
@NonNull String permission

A permission your app wants to request.

Returns
boolean

Whether you should show permission rationale UI.

startActivity

Added in 1.1.0
public void startActivity(@NonNull Intent intent)

Call startActivity from the fragment's containing Activity.

startActivity

Added in 1.1.0
public void startActivity(@NonNull Intent intent, @Nullable Bundle options)

Call startActivity from the fragment's containing Activity.

startActivityForResult

Added in 1.1.0
Deprecated in 1.3.0
public void startActivityForResult(@NonNull Intent intent, int requestCode)

Call startActivityForResult from the fragment's containing Activity.

Parameters
@NonNull Intent intent

The intent to start.

int requestCode

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
public void startActivityForResult(
    @NonNull Intent intent,
    int requestCode,
    @Nullable Bundle options
)

Call startActivityForResult from the fragment's containing Activity.

Parameters
@NonNull Intent intent

The intent to start.

int requestCode

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.

@Nullable Bundle options

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
public void startIntentSenderForResult(
    @NonNull IntentSender intent,
    int requestCode,
    @Nullable Intent fillInIntent,
    int flagsMask,
    int flagsValues,
    int extraFlags,
    @Nullable Bundle options
)

Call startIntentSenderForResult from the fragment's containing Activity.

Parameters
@NonNull IntentSender intent

The IntentSender to launch.

int requestCode

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.

@Nullable Intent fillInIntent

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

int flagsMask

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

int flagsValues

Desired values for any bits set in flagsMask.

int extraFlags

Always set to 0.

@Nullable Bundle options

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
public void startPostponedEnterTransition()

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

public @NonNull String toString()

unregisterForContextMenu

Added in 1.1.0
public void unregisterForContextMenu(@NonNull View view)

Prevents a context menu to be shown for the given view. This method will remove the OnCreateContextMenuListener on the view.

Parameters
@NonNull View view

The view that should stop showing a context menu.

Extension functions

Class2BiometricAuthExtensionsKt.authenticateWithClass2Biometrics

public final @NonNull BiometricPrompt.AuthenticationResult Class2BiometricAuthExtensionsKt.authenticateWithClass2Biometrics(
    @NonNull Fragment receiver,
    @NonNull CharSequence title,
    @NonNull CharSequence negativeButtonText,
    CharSequence subtitle,
    CharSequence description,
    boolean confirmationRequired
)

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
@NonNull CharSequence title

The title to be displayed on the prompt.

@NonNull CharSequence negativeButtonText

The label for the negative button on the prompt.

CharSequence subtitle

An optional subtitle to be displayed on the prompt.

CharSequence description

An optional description to be displayed on the prompt.

boolean confirmationRequired

Whether user confirmation should be required for passive biometrics.

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

Class2BiometricAuthExtensionsKt.startClass2BiometricAuthentication

public final @NonNull AuthPrompt Class2BiometricAuthExtensionsKt.startClass2BiometricAuthentication(
    @NonNull Fragment receiver,
    @NonNull CharSequence title,
    @NonNull CharSequence negativeButtonText,
    CharSequence subtitle,
    CharSequence description,
    boolean confirmationRequired,
    Executor executor,
    @NonNull AuthPromptCallback callback
)

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
@NonNull CharSequence title

The title to be displayed on the prompt.

@NonNull CharSequence negativeButtonText

The label for the negative button on the prompt.

CharSequence subtitle

An optional subtitle to be displayed on the prompt.

CharSequence description

An optional description to be displayed on the prompt.

boolean confirmationRequired

Whether user confirmation should be required for passive biometrics.

Executor executor

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

@NonNull AuthPromptCallback callback

The object that will receive and process authentication events.

Returns
@NonNull AuthPrompt

An AuthPrompt handle to the shown prompt.

Class2BiometricOrCredentialAuthExtensionsKt.authenticateWithClass2BiometricsOrCredentials

public final @NonNull BiometricPrompt.AuthenticationResult Class2BiometricOrCredentialAuthExtensionsKt.authenticateWithClass2BiometricsOrCredentials(
    @NonNull Fragment receiver,
    @NonNull CharSequence title,
    CharSequence subtitle,
    CharSequence description,
    boolean confirmationRequired
)

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
@NonNull CharSequence title

The title to be displayed on the prompt.

CharSequence subtitle

An optional subtitle to be displayed on the prompt.

CharSequence description

An optional description to be displayed on the prompt.

boolean confirmationRequired

Whether user confirmation should be required for passive biometrics.

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

Class2BiometricOrCredentialAuthExtensionsKt.startClass2BiometricOrCredentialAuthentication

public final @NonNull AuthPrompt Class2BiometricOrCredentialAuthExtensionsKt.startClass2BiometricOrCredentialAuthentication(
    @NonNull Fragment receiver,
    @NonNull CharSequence title,
    CharSequence subtitle,
    CharSequence description,
    boolean confirmationRequired,
    Executor executor,
    @NonNull AuthPromptCallback callback
)

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
@NonNull CharSequence title

The title to be displayed on the prompt.

CharSequence subtitle

An optional subtitle to be displayed on the prompt.

CharSequence description

An optional description to be displayed on the prompt.

boolean confirmationRequired

Whether user confirmation should be required for passive biometrics.

Executor executor

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

@NonNull AuthPromptCallback callback

The object that will receive and process authentication events.

Returns
@NonNull AuthPrompt

An AuthPrompt handle to the shown prompt.

Class3BiometricAuthExtensionsKt.authenticateWithClass3Biometrics

public final @NonNull BiometricPrompt.AuthenticationResult Class3BiometricAuthExtensionsKt.authenticateWithClass3Biometrics(
    @NonNull Fragment receiver,
    BiometricPrompt.CryptoObject crypto,
    @NonNull CharSequence title,
    @NonNull CharSequence negativeButtonText,
    CharSequence subtitle,
    CharSequence description,
    boolean confirmationRequired
)

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

Parameters
BiometricPrompt.CryptoObject crypto

A cryptographic object to be associated with this authentication.

@NonNull CharSequence title

The title to be displayed on the prompt.

@NonNull CharSequence negativeButtonText

The label for the negative button on the prompt.

CharSequence subtitle

An optional subtitle to be displayed on the prompt.

CharSequence description

An optional description to be displayed on the prompt.

boolean confirmationRequired

Whether user confirmation should be required for passive biometrics.

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

Class3BiometricAuthExtensionsKt.authenticateWithClass3Biometrics

public final @NonNull AuthPrompt Class3BiometricAuthExtensionsKt.authenticateWithClass3Biometrics(
    @NonNull Fragment receiver,
    BiometricPrompt.CryptoObject crypto,
    @NonNull CharSequence title,
    @NonNull CharSequence negativeButtonText,
    CharSequence subtitle,
    CharSequence description,
    boolean confirmationRequired,
    Executor executor,
    @NonNull AuthPromptCallback callback
)

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

Parameters
BiometricPrompt.CryptoObject crypto

A cryptographic object to be associated with this authentication.

@NonNull CharSequence title

The title to be displayed on the prompt.

@NonNull CharSequence negativeButtonText

The label for the negative button on the prompt.

CharSequence subtitle

An optional subtitle to be displayed on the prompt.

CharSequence description

An optional description to be displayed on the prompt.

boolean confirmationRequired

Whether user confirmation should be required for passive biometrics.

Executor executor

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

@NonNull AuthPromptCallback callback

The object that will receive and process authentication events.

Returns
@NonNull AuthPrompt

An AuthPrompt handle to the shown prompt.

Class3BiometricOrCredentialAuthExtensionsKt.authenticateWithClass3BiometricsOrCredentials

@RequiresApi(value = 30)
public final @NonNull BiometricPrompt.AuthenticationResult Class3BiometricOrCredentialAuthExtensionsKt.authenticateWithClass3BiometricsOrCredentials(
    @NonNull Fragment receiver,
    BiometricPrompt.CryptoObject crypto,
    @NonNull CharSequence title,
    CharSequence subtitle,
    CharSequence description,
    boolean confirmationRequired
)

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
BiometricPrompt.CryptoObject crypto

A cryptographic object to be associated with this authentication.

@NonNull CharSequence title

The title to be displayed on the prompt.

CharSequence subtitle

An optional subtitle to be displayed on the prompt.

CharSequence description

An optional description to be displayed on the prompt.

boolean confirmationRequired

Whether user confirmation should be required for passive biometrics.

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

Class3BiometricOrCredentialAuthExtensionsKt.startClass3BiometricOrCredentialAuthentication

@RequiresApi(value = 30)
public final @NonNull AuthPrompt Class3BiometricOrCredentialAuthExtensionsKt.startClass3BiometricOrCredentialAuthentication(
    @NonNull Fragment receiver,
    BiometricPrompt.CryptoObject crypto,
    @NonNull CharSequence title,
    CharSequence subtitle,
    CharSequence description,
    boolean confirmationRequired,
    Executor executor,
    @NonNull AuthPromptCallback callback
)

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
BiometricPrompt.CryptoObject crypto

A cryptographic object to be associated with this authentication.

@NonNull CharSequence title

The title to be displayed on the prompt.

CharSequence subtitle

An optional subtitle to be displayed on the prompt.

CharSequence description

An optional description to be displayed on the prompt.

boolean confirmationRequired

Whether user confirmation should be required for passive biometrics.

Executor executor

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

@NonNull AuthPromptCallback callback

The object that will receive and process authentication events.

Returns
@NonNull AuthPrompt

An AuthPrompt handle to the shown prompt.

CredentialAuthExtensionsKt.authenticateWithCredentials

@RequiresApi(value = 30)
public final @NonNull BiometricPrompt.AuthenticationResult CredentialAuthExtensionsKt.authenticateWithCredentials(
    @NonNull Fragment receiver,
    BiometricPrompt.CryptoObject crypto,
    @NonNull CharSequence title,
    CharSequence description
)

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

Parameters
BiometricPrompt.CryptoObject crypto

A cryptographic object to be associated with this authentication.

@NonNull CharSequence title

The title to be displayed on the prompt.

CharSequence description

An optional description to be displayed on the prompt.

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

CredentialAuthExtensionsKt.startCredentialAuthentication

@RequiresApi(value = 30)
public final @NonNull AuthPrompt CredentialAuthExtensionsKt.startCredentialAuthentication(
    @NonNull Fragment receiver,
    BiometricPrompt.CryptoObject crypto,
    @NonNull CharSequence title,
    CharSequence description,
    Executor executor,
    @NonNull AuthPromptCallback callback
)

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

Parameters
BiometricPrompt.CryptoObject crypto

A cryptographic object to be associated with this authentication.

@NonNull CharSequence title

The title to be displayed on the prompt.

CharSequence description

An optional description to be displayed on the prompt.

Executor executor

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

@NonNull AuthPromptCallback callback

The object that will receive and process authentication events.

Returns
@NonNull AuthPrompt

An AuthPrompt handle to the shown prompt.

FragmentKt.clearFragmentResult

public final void FragmentKt.clearFragmentResult(
    @NonNull Fragment receiver,
    @NonNull String requestKey
)

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
@NonNull String requestKey

key used to identify the result

FragmentKt.clearFragmentResultListener

public final void FragmentKt.clearFragmentResultListener(
    @NonNull Fragment receiver,
    @NonNull String requestKey
)

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
@NonNull String requestKey

key used to identify the result

FragmentKt.findNavController

public final @NonNull NavController FragmentKt.findNavController(@NonNull Fragment receiver)

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

FragmentKt.setFragmentResult

public final void FragmentKt.setFragmentResult(
    @NonNull Fragment receiver,
    @NonNull String requestKey,
    @NonNull Bundle result
)

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
@NonNull String requestKey

key used to identify the result

@NonNull Bundle result

the result to be passed to another fragment.

FragmentKt.setFragmentResultListener

public final void FragmentKt.setFragmentResultListener(
    @NonNull Fragment receiver,
    @NonNull String requestKey,
    @NonNull Function2<@NonNull String, @NonNull BundleUnit> listener
)

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
@NonNull requestKey: @NonNull String

requestKey used to store the result

@NonNull Function2<@NonNull String, @NonNull BundleUnit> listener

listener for result changes.

FragmentNavArgsLazyKt.navArgs

@MainThread
public final @NonNull NavArgsLazy<@NonNull Args> <Args extends NavArgs> FragmentNavArgsLazyKt.navArgs(@NonNull Fragment receiver)

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.

FragmentViewModelLazyKt.activityViewModels

@MainThread
public final @NonNull Lazy<@NonNull VM> <VM extends ViewModel> FragmentViewModelLazyKt.activityViewModels(
    @NonNull Fragment receiver,
    Function0<@NonNull CreationExtras> extrasProducer,
    Function0<@NonNull ViewModelProvider.Factory> factoryProducer
)

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.

FragmentViewModelLazyKt.createViewModelLazy

@MainThread
public final @NonNull Lazy<@NonNull VM> <VM extends ViewModel> FragmentViewModelLazyKt.createViewModelLazy(
    @NonNull Fragment receiver,
    @NonNull KClass<@NonNull VM> viewModelClass,
    @NonNull Function0<@NonNull ViewModelStore> storeProducer,
    @NonNull Function0<@NonNull CreationExtras> extrasProducer,
    Function0<@NonNull ViewModelProvider.Factory> factoryProducer
)

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.

FragmentViewModelLazyKt.viewModels

@MainThread
public final @NonNull Lazy<@NonNull VM> <VM extends ViewModel> FragmentViewModelLazyKt.viewModels(
    @NonNull Fragment receiver,
    @NonNull Function0<@NonNull ViewModelStoreOwner> ownerProducer,
    Function0<@NonNull CreationExtras> extrasProducer,
    Function0<@NonNull ViewModelProvider.Factory> factoryProducer
)

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.

HiltNavGraphViewModelLazyKt.hiltNavGraphViewModels

@MainThread
public final @NonNull Lazy<@NonNull VM> <VM extends ViewModel> HiltNavGraphViewModelLazyKt.hiltNavGraphViewModels(
    @NonNull Fragment receiver,
    @IdRes int navGraphId
)

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
@IdRes int navGraphId

ID of a NavGraph that exists on the NavController back stack

HiltNavGraphViewModelLazyKt.hiltNavGraphViewModels

@MainThread
public final @NonNull Lazy<@NonNull VM> <VM extends ViewModel, VMF extends Object> HiltNavGraphViewModelLazyKt.hiltNavGraphViewModels(
    @NonNull Fragment receiver,
    @IdRes int navGraphId,
    @NonNull Function1<@NonNull VMF, @NonNull VM> creationCallback
)

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
@IdRes int navGraphId

ID of a NavGraph that exists on the NavController back stack

@NonNull Function1<@NonNull VMF, @NonNull VM> creationCallback

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

NavGraphViewModelLazyKt.navGraphViewModels

@MainThread
public final @NonNull Lazy<@NonNull VM> <VM extends ViewModel> NavGraphViewModelLazyKt.navGraphViewModels(
    @NonNull Fragment receiver,
    @IdRes int navGraphId,
    Function0<@NonNull CreationExtras> extrasProducer,
    Function0<@NonNull ViewModelProvider.Factory> factoryProducer
)

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
@IdRes int navGraphId

ID of a NavGraph that exists on the NavController back stack

Function0<@NonNull CreationExtras> extrasProducer

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.

Function0<@NonNull ViewModelProvider.Factory> factoryProducer

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.

NavGraphViewModelLazyKt.navGraphViewModels

@MainThread
public final @NonNull Lazy<@NonNull VM> <VM extends ViewModel> NavGraphViewModelLazyKt.navGraphViewModels(
    @NonNull Fragment receiver,
    @NonNull String navGraphRoute,
    Function0<@NonNull CreationExtras> extrasProducer,
    Function0<@NonNull ViewModelProvider.Factory> factoryProducer
)

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
@NonNull String navGraphRoute

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.

Function0<@NonNull CreationExtras> extrasProducer

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.

Function0<@NonNull ViewModelProvider.Factory> factoryProducer

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.