Fragment
public class Fragment implements ComponentCallbacks, View.OnCreateContextMenuListener, LifecycleOwner, ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner, ActivityResultCaller, ContextAware
AbstractListDetailFragment |
A fragment supports adaptive two-pane layout. |
AbstractProgressFragment |
The base class for |
AmbientModeSupport |
This class is deprecated. Use |
BrandedSupportFragment |
Fragment class for managing search and branding using a view that implements |
DialogFragment |
A fragment that displays a dialog window, floating in the foreground of its activity's window. |
GuidedStepSupportFragment |
A GuidedStepSupportFragment is used to guide the user through a decision or series of decisions. |
HeadersSupportFragment |
An fragment containing a list of row headers. |
LeanbackPreferenceDialogFragmentCompat |
A fragment that shows |
LeanbackSettingsFragmentCompat |
This fragment provides a container for displaying a |
ListFragment |
Static library support version of the framework's |
MediaRouteDiscoveryFragment |
Media route discovery fragment. |
NavHostFragment |
NavHostFragment provides an area within your layout for self-contained navigation to occur. |
OnboardingSupportFragment |
An OnboardingSupportFragment provides a common and simple way to build onboarding screen for applications. |
PdfViewerFragment |
A Fragment that renders a PDF document. |
PlaybackSupportFragment |
A fragment for displaying playback controls and related content. |
PreferenceFragmentCompat |
A PreferenceFragmentCompat is the entry point to using the Preference library. |
PreferenceHeaderFragmentCompat |
|
RowsSupportFragment |
An ordered set of rows of leanback widgets. |
SearchSupportFragment |
A fragment to handle searches. |
AppCompatDialogFragment |
A special version of |
BaseLeanbackPreferenceFragmentCompat |
This fragment provides a preference fragment with leanback-style behavior, suitable for embedding into broader UI elements. |
BaseSupportFragment |
Base class for leanback Fragments. |
BrowseSupportFragment |
A fragment for creating Leanback browse screens. |
DefaultProgressFragment |
The default |
DetailsSupportFragment |
A fragment for creating Leanback details screens. |
DynamicNavHostFragment |
The |
EditTextPreferenceDialogFragmentCompat |
|
EditablePdfViewerFragment |
A |
ErrorSupportFragment |
A fragment for displaying an error indication. |
LeanbackEditTextPreferenceDialogFragmentCompat |
Implemented a dialog to input text. |
LeanbackListPreferenceDialogFragmentCompat |
Implemented a dialog to show |
LeanbackPreferenceFragmentCompat |
This fragment provides a fully decorated leanback-style preference fragment, including a list background and header. |
ListPreferenceDialogFragmentCompat |
|
MediaRouteChooserDialogFragment |
Media route chooser dialog fragment. |
MediaRouteControllerDialogFragment |
Media route controller dialog fragment. |
MultiSelectListPreferenceDialogFragmentCompat |
|
PreferenceDialogFragmentCompat |
Abstract base class which presents a dialog associated with a |
VerticalGridSupportFragment |
A fragment for creating leanback vertical grids. |
VideoSupportFragment |
Subclass of |
Static library support version of the framework's android.app.Fragment. Used to write apps that run on platforms prior to Android 3.0. When running on Android 3.0 or above, this implementation is still used; it does not try to switch to the framework's implementation. See the framework android.app.Fragment documentation for a class overview.
The main differences when using this support version instead of the framework version are:
- Your activity must extend
FragmentActivity - You must call
getSupportFragmentManagerto get theFragmentManager
Summary
Nested types |
|---|
public class Fragment.InstantiationException extends RuntimeExceptionThrown by |
public class Fragment.SavedState implements ParcelableState information that has been retrieved from a fragment instance through |
Public constructors |
|---|
Fragment()Constructor used by the default |
@ContentViewAlternate constructor that can be called from your default, no argument constructor to provide a default layout that will be inflated by |
Public methods |
|
|---|---|
void |
Add a new |
void |
dump(Print the Fragments's state into the given stream. |
final boolean |
Subclasses can not override equals(). |
final @Nullable FragmentActivity |
Return the |
boolean |
Returns whether the the exit transition and enter transition overlap or not. |
boolean |
Returns whether the the return transition and reenter transition overlap or not. |
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 |
@NonNull CreationExtras |
Returns the default |
@NonNull ViewModelProvider.Factory |
Returns the default |
@Nullable Object |
Returns the Transition that will be used to move Views into the initial scene. |
@Nullable Object |
Returns the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack. |
final @Nullable FragmentManager |
This method is deprecated. This has been removed in favor of |
final @Nullable Object |
getHost()Return the host object of this fragment. |
final int |
getId()Return the identifier this fragment is known by. |
final @NonNull LayoutInflater |
Returns the cached LayoutInflater used to inflate Views of this Fragment. |
@NonNull Lifecycle |
Returns the Lifecycle of the provider. |
@NonNull LoaderManager |
This method is deprecated. |
final @Nullable Fragment |
Returns the parent Fragment containing this Fragment. |
final @NonNull FragmentManager |
Return the FragmentManager for interacting with fragments associated with this fragment's activity. |
@Nullable Object |
Returns the Transition that will be used to move Views in to the scene when returning due to popping a back stack. |
final @NonNull Resources |
Return |
final 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 |
The |
@Nullable Object |
Returns the Transition that will be used for shared elements transferred into the content Scene. |
@Nullable Object |
Return the Transition that will be used for shared elements transferred back during a pop of the back stack. |
final @NonNull String |
Return a localized string from the application's package's default string table. |
final @NonNull String |
Return a localized formatted string from the application's package's default string table, substituting the format arguments as defined in |
final @Nullable String |
getTag()Get the tag name of the fragment, if specified. |
final @Nullable Fragment |
This method is deprecated. Instead of using a target fragment to pass results, use |
final int |
This method is deprecated. When using the target fragment replacement of |
final @NonNull CharSequence |
Return a localized, styled CharSequence from the application's package's default string table. |
boolean |
This method is deprecated. Use |
@Nullable View |
getView()Get the root view for the fragment's layout (the one returned by |
@NonNull LifecycleOwner |
Get a |
@NonNull LiveData<LifecycleOwner> |
Retrieve a |
@NonNull ViewModelStore |
Returns the |
final int |
hashCode()Subclasses can not override hashCode(). |
static @NonNull Fragment |
This method is deprecated. Use |
static @NonNull Fragment |
This method is deprecated. Use |
final boolean |
isAdded()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 |
isHidden()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 |
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 |
@MainThreadThis method is deprecated. use |
void |
This method is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an |
void |
@MainThreadThis method is deprecated. See |
void |
@MainThreadCalled when a fragment is first attached to its context. |
void |
@MainThreadThis method is deprecated. The responsibility for listening for fragments being attached has been moved to FragmentManager. |
void |
@CallSuper |
boolean |
This hook is called whenever an item in a context menu is selected. |
void |
@MainThreadCalled to do initial creation of a fragment. |
@Nullable Animation |
@MainThreadCalled when a fragment loads an animation. |
@Nullable Animator |
@MainThreadCalled when a fragment loads an animator. |
void |
@MainThreadCalled when a context menu for the |
void |
@MainThreadThis method is deprecated.
|
@Nullable View |
@MainThreadCalled to have the fragment instantiate its user interface view. |
void |
Called when the fragment is no longer in use. |
void |
This method is deprecated.
|
void |
Called when the view previously created by |
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 |
@MainThreadCalled when the hidden state (as returned by |
void |
@UiThreadThis method is deprecated. See |
void |
@UiThreadCalled when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity. |
void |
This method is deprecated. |
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.
|
void |
@MainThreadThis method is deprecated.
|
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.
|
void |
@MainThreadCallback for when the primary navigation state of this Fragment has changed. |
void |
This method is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an |
void |
Called when the fragment is visible to the user and actively running. |
void |
@MainThreadCalled to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance if its process is restarted. |
void |
Called when the Fragment is visible to the user. |
void |
Called when the Fragment is no longer started. |
void |
@MainThreadCalled immediately after |
void |
@MainThreadCalled when all saved state has been restored into the view hierarchy of the fragment. |
@Nullable Context |
Get the |
void |
Postpone the entering Fragment transition until |
final void |
postponeEnterTransition(long duration, @NonNull TimeUnit timeUnit)Postpone the entering Fragment transition for a given amount of time and then call |
final @NonNull ActivityResultLauncher<I> |
@MainThread
Register a request to |
final @NonNull ActivityResultLauncher<I> |
@MainThreadRegister a request to |
void |
registerForContextMenu(@NonNull View view)Registers a context menu to be shown for the given view (multiple views can show the context menu). |
void |
Remove a |
final void |
This method is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an |
final @NonNull FragmentActivity |
Return the |
final @NonNull Bundle |
Return the arguments supplied when the fragment was instantiated. |
final @NonNull Context |
Return the |
final @NonNull FragmentManager |
This method is deprecated. This has been renamed to |
final @NonNull Object |
Return the host object of this fragment. |
final @NonNull Fragment |
Returns the parent Fragment containing this Fragment. |
final @NonNull View |
Get the root view for the fragment's layout (the one returned by |
void |
setAllowEnterTransitionOverlap(boolean allow)Sets whether the the exit transition and enter transition overlap or not. |
void |
setAllowReturnTransitionOverlap(boolean allow)Sets whether the the return transition and reenter transition overlap or not. |
void |
setArguments(@Nullable Bundle args)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 |
setEnterTransition(@Nullable Object transition)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 |
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. |
void |
This method is deprecated. This method is no longer needed when using a |
void |
Set the initial saved state that this Fragment should restore itself from when first being constructed, as returned by |
void |
setMenuVisibility(boolean menuVisible)Set a hint for whether this fragment's menu should be visible. |
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. |
void |
This method is deprecated. Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment. |
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. |
void |
setSharedElementEnterTransition(@Nullable Object transition)Sets the Transition that will be used for shared elements transferred into the content Scene. |
void |
setSharedElementReturnTransition(@Nullable Object transition)Sets the Transition that will be used for shared elements transferred back during a pop of the back stack. |
void |
This method is deprecated. Instead of using a target fragment to pass results, the fragment requesting a result should use |
void |
This method is deprecated. If you are manually calling this method, use |
boolean |
shouldShowRequestPermissionRationale(@NonNull String permission)Gets whether you should show UI with rationale before requesting a permission. |
void |
startActivity(@NonNull Intent intent)Call startActivity from the fragment's containing Activity. |
void |
startActivity(@NonNull Intent intent, @Nullable Bundle options)Call startActivity from the fragment's containing Activity. |
void |
This method is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an |
void |
This method is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an |
void |
This method is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an |
void |
Begin postponed transitions after |
@NonNull String |
toString() |
void |
unregisterForContextMenu(@NonNull View view)Prevents a context menu to be shown for the given view. |
Extension functions |
|
|---|---|
final @NonNull AuthenticationResultLauncher |
AuthenticationUtils.registerForAuthenticationResult(Returns an |
final @NonNull AuthenticationResultLauncher |
AuthenticationUtils.registerForAuthenticationResult(Returns an |
final void |
FragmentKt.clearFragmentResult(Clears the stored result for the given requestKey. |
final void |
FragmentKt.clearFragmentResultListener(Clears the stored |
final @NonNull NavController |
FragmentKt.findNavController(@NonNull Fragment receiver)Find a |
final void |
FragmentKt.setFragmentResult(Sets the given result for the |
final void |
FragmentKt.setFragmentResultListener(Sets the |
final @NonNull NavArgsLazy<@NonNull Args> |
@MainThreadReturns a |
final @NonNull Lazy<@NonNull VM> |
@MainThreadReturns a property delegate to access parent activity's |
final @NonNull Lazy<@NonNull VM> |
@MainThreadHelper method for creation of |
final @NonNull Lazy<@NonNull VM> |
@MainThreadReturns a property delegate to access |
final @NonNull Lazy<@NonNull VM> |
@MainThreadReturns a property delegate to access a HiltViewModel -annotated |
final @NonNull Lazy<@NonNull VM> |
@MainThreadReturns a property delegate to access a HiltViewModel -annotated |
final @NonNull Lazy<@NonNull VM> |
@MainThreadReturns a property delegate to access a |
final @NonNull Lazy<@NonNull VM> |
@MainThreadReturns a property delegate to access a |
Public constructors
Fragment
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
@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); } }
set a custom FragmentFactory if you want to use a non-default constructor to ensure that your constructor is called when the fragment is re-instantiated.
| See also | |
|---|---|
Fragment |
|
onCreateView |
Public methods
addOnContextAvailableListener
public void addOnContextAvailableListener(
@NonNull OnContextAvailableListener listener
)
Add a new OnContextAvailableListener for receiving a callback for when this class is associated with a android.content.Context.
Listeners are triggered in the order they are added when added before the Context is available. Listeners added after the context has been made available will have the Context synchronously delivered to them as part of this call.
| Parameters | |
|---|---|
@NonNull OnContextAvailableListener listener |
The listener that should be added. |
| See also | |
|---|---|
removeOnContextAvailableListener |
dump
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
public final boolean equals(@Nullable Object o)
Subclasses can not override equals().
getActivity
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
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
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
public final @Nullable Bundle getArguments()
Return the arguments supplied when the fragment was instantiated, if any.
getChildFragmentManager
public final @NonNull FragmentManager getChildFragmentManager()
Return a private FragmentManager for placing and managing Fragments inside of this Fragment.
getContext
public @Nullable Context getContext()
Return the Context this fragment is currently associated with.
| See also | |
|---|---|
requireContext |
getDefaultViewModelCreationExtras
@CallSuper
public @NonNull CreationExtras getDefaultViewModelCreationExtras()
Returns the default CreationExtras that should be passed into ViewModelProvider.Factory.create when no overriding CreationExtras were passed to the ViewModelProvider constructors.
The Fragment's arguments when this is first called will be used as the defaults to any androidx.lifecycle.SavedStateHandle passed to a view model created using this extra.
getDefaultViewModelProviderFactory
public @NonNull ViewModelProvider.Factory getDefaultViewModelProviderFactory()
Returns the default ViewModelProvider.Factory that should be used when no custom Factory is provided to the ViewModelProvider constructors.
getEnterTransition
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.
getExitTransition
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.
public final @Nullable FragmentManagergetFragmentManager()
Return the FragmentManager for interacting with fragments associated with this fragment's activity. Note that this will be non-null slightly before getActivity, during the time from when the fragment is placed in a FragmentTransaction until it is committed and attached to its activity.
If this Fragment is a child of another Fragment, the FragmentManager returned here will be the parent's getChildFragmentManager.
| See also | |
|---|---|
getParentFragmentManager |
getHost
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
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
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
public @NonNull Lifecycle getLifecycle()
Returns the Lifecycle of the provider.
Overriding this method is no longer supported and this method will be made final in a future version of Fragment.
getParentFragment
public final @Nullable Fragment getParentFragment()
Returns the parent Fragment containing this Fragment. If this Fragment is attached directly to an Activity, returns null.
getParentFragmentManager
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
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.
getResources
public final @NonNull Resources getResources()
Return requireActivity().getResources().
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. |
| See also | |
|---|---|
setRetainInstance |
getReturnTransition
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.
getSavedStateRegistry
public final @NonNull SavedStateRegistry getSavedStateRegistry()
The SavedStateRegistry owned by this SavedStateRegistryOwner
getSharedElementEnterTransition
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.
getSharedElementReturnTransition
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.
getString
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.
getTag
public final @Nullable String getTag()
Get the tag name of the fragment, if specified.
public final @Nullable FragmentgetTargetFragment()
Return the target fragment set by setTargetFragment.
getText
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 |
public boolean getUserVisibleHint()| Returns | |
|---|---|
boolean |
The current value of the user-visible hint on this fragment. |
| See also | |
|---|---|
setUserVisibleHint |
getView
public @Nullable View getView()
Get the root view for the fragment's layout (the one returned by onCreateView), if provided.
getViewLifecycleOwner
@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:
createdafteronViewStateRestoredstartedafteronStartresumedafteronResumepausedbeforeonPausestoppedbeforeonStopdestroyedbeforeonDestroyView
onCreateView under the condition that you must return a non-null view (an IllegalStateException will be thrown if you access the view lifecycle but don't return a non-null view).
The view lifecycle remains valid through the call to onDestroyView, after which getView will return null, the view lifecycle will be destroyed, and this method will throw an IllegalStateException. Consider using getViewLifecycleOwnerLiveData or runOnCommit to receive a callback for when the Fragment's view lifecycle is available.
This should only be called on the main thread.
Overriding this method is no longer supported and this method will be made final in a future version of Fragment.
| Returns | |
|---|---|
@NonNull LifecycleOwner |
A |
| Throws | |
|---|---|
java.lang.IllegalStateException |
if the |
getViewLifecycleOwnerLiveData
public @NonNull LiveData<LifecycleOwner> getViewLifecycleOwnerLiveData()
Retrieve a LiveData which allows you to observe the lifecycle of the Fragment's View.
This will be set to the new LifecycleOwner after onCreateView returns a non-null View and will set to null after onDestroyView.
Overriding this method is no longer supported and this method will be made final in a future version of Fragment.
| Returns | |
|---|---|
@NonNull LiveData<LifecycleOwner> |
A LiveData that changes in sync with |
getViewModelStore
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 |
| Throws | |
|---|---|
java.lang.IllegalStateException |
if called before the Fragment is attached i.e., before onAttach(). |
public static @NonNull Fragmentinstantiate(@NonNull Context context, @NonNull String fname)
Like instantiate but with a null argument Bundle.
public static @NonNull Fragmentinstantiate(
@NonNull Context context,
@NonNull String fname,
@Nullable Bundle args
)
Create a new instance of a Fragment with the given class name. This is the same as calling its empty constructor, setting the ClassLoader on the supplied arguments, then calling setArguments.
| Parameters | |
|---|---|
@NonNull Context context |
The calling context being used to instantiate the fragment. This is currently just used to get its ClassLoader. |
@NonNull String fname |
The class name of the fragment to instantiate. |
@Nullable Bundle args |
Bundle of arguments to supply to the fragment, which it can retrieve with |
| 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
public final boolean isAdded()
Return true if the fragment is currently added to its activity.
isDetached
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
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
public final boolean isInLayout()
Return true if the layout is included as part of an activity view hierarchy via the
isRemoving
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
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
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
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.
@MainThread
@CallSuper
public voidonActivityCreated(@Nullable Bundle savedInstanceState)
Called when the fragment's activity has been created and this fragment's view hierarchy instantiated. It can be used to do final initialization once these pieces are in place, such as retrieving views or restoring state. It is also useful for fragments that use setRetainInstance to retain their instance, as this callback tells the fragment when it is fully associated with the new activity instance. This is called after onCreateView and before onViewStateRestored.
public voidonActivityResult(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 originally 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"). |
@MainThread
@CallSuper
public voidonAttach(@NonNull Activity activity)
Called when a fragment is first attached to its activity. onCreate will be called after this.
onAttach
@MainThread
@CallSuper
public void onAttach(@NonNull Context context)
Called when a fragment is first attached to its context. onCreate will be called after this.
@MainThread
public voidonAttachFragment(@NonNull Fragment childFragment)
Called when a fragment is attached as a child of this fragment.
This is called after the attached fragment's onAttach and before the attached fragment's onCreate if the fragment has not yet had a previous call to onCreate.
onConfigurationChanged
@CallSuper
public void onConfigurationChanged(@NonNull Configuration newConfig)
onContextItemSelected
@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.
| Returns | |
|---|---|
boolean |
boolean Return false to allow normal context menu processing to proceed, true to consume it here. |
onCreate
@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.
onCreateAnimation
@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 |
boolean enter |
|
int nextAnim |
The resource set in |
onCreateAnimator
@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 |
boolean enter |
|
int nextAnim |
The resource set in |
onCreateContextMenu
@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.
@MainThread
public voidonCreateOptionsMenu(@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.
onCreateView
@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. |
onDestroy
@MainThread
@CallSuper
public void onDestroy()
Called when the fragment is no longer in use. This is called after onStop and before onDetach.
@MainThread
public voidonDestroyOptionsMenu()
Called when this fragment's option menu items are no longer being included in the overall options menu. Receiving this call means that the menu needed to be rebuilt, but this fragment's items were not included in the newly built menu (its onCreateOptionsMenu was not called).
onDestroyView
@MainThread
@CallSuper
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
@MainThread
@CallSuper
public void onDetach()
Called when the fragment is no longer attached to its activity. This is called after onDestroy.
onGetLayoutInflater
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
@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. |
@UiThread
@CallSuper
public voidonInflate(
@NonNull Activity activity,
@NonNull AttributeSet attrs,
@Nullable Bundle savedInstanceState
)
Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity.
onInflate
@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(); } }
onMultiWindowModeChanged
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. |
@MainThread
public booleanonOptionsItemSelected(@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.
| Returns | |
|---|---|
boolean |
boolean Return false to allow normal menu processing to proceed, true to consume it here. |
| See also | |
|---|---|
onCreateOptionsMenu |
@MainThread
public voidonOptionsMenuClosed(@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).
onPause
@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
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. |
@MainThread
public voidonPrepareOptionsMenu(@NonNull Menu menu)
Prepare the Fragment host's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents. See Activity.onPrepareOptionsMenu for more information.
| Parameters | |
|---|---|
@NonNull Menu menu |
The options menu as last shown or first initialized by onCreateOptionsMenu(). |
| See also | |
|---|---|
setHasOptionsMenu |
|
onCreateOptionsMenu |
onPrimaryNavigationFragmentChanged
@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 |
public voidonRequestPermissionsResult(
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 |
@NonNull String[] permissions |
The requested permissions. Never null. |
@NonNull int[] grantResults |
The grant results for the corresponding permissions which is either |
| See also | |
|---|---|
requestPermissions |
onResume
@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
@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.
onStart
@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
@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
@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 |
@Nullable Bundle savedInstanceState |
If non-null, this fragment is being re-constructed from a previous saved state as given here. |
onViewStateRestored
@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.
peekAvailableContext
public @Nullable Context peekAvailableContext()
Get the Context if it is currently available. If this returns null, you can use addOnContextAvailableListener to receive a callback for when it available.
postponeEnterTransition
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
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.
registerForActivityResult
@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
@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 |
@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
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.
| See also | |
|---|---|
unregisterForContextMenu |
removeOnContextAvailableListener
public void removeOnContextAvailableListener(
@NonNull OnContextAvailableListener listener
)
Remove a OnContextAvailableListener previously added via addOnContextAvailableListener.
| Parameters | |
|---|---|
@NonNull OnContextAvailableListener listener |
The listener that should be removed. |
| See also | |
|---|---|
addOnContextAvailableListener |
public final voidrequestPermissions(@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 |
requireActivity
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
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
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 |
public final @NonNull FragmentManagerrequireFragmentManager()
Return the FragmentManager for interacting with fragments associated with this fragment's activity. Note that this will be available slightly before getActivity, during the time from when the fragment is placed in a FragmentTransaction until it is committed and attached to its activity.
If this Fragment is a child of another Fragment, the FragmentManager returned here will be the parent's getChildFragmentManager.
| Throws | |
|---|---|
java.lang.IllegalStateException |
if not associated with a transaction or host. |
| See also | |
|---|---|
getParentFragmentManager |
requireHost
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
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. |
| See also | |
|---|---|
getParentFragment |
requireView
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 |
| See also | |
|---|---|
getView |
setAllowEnterTransitionOverlap
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
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
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
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
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. |
setExitSharedElementCallback
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
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. |
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
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
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
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. |
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:
onDestroywill not be called (butonDetachstill will be, because the fragment is being detached from its current activity).onCreatewill not be called since the fragment is not being re-created.onAttachandonActivityCreatedwill still be called.
| Parameters | |
|---|---|
boolean retain |
|
| See also | |
|---|---|
getRetainInstance |
setReturnTransition
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. |
setSharedElementEnterTransition
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. |
setSharedElementReturnTransition
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. |
public voidsetTargetFragment(@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 |
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
public boolean shouldShowRequestPermissionRationale(@NonNull String permission)
Gets whether you should show UI with rationale before requesting a permission.
| Returns | |
|---|---|
boolean |
Whether you should show permission rationale UI. |
startActivity
public void startActivity(@NonNull Intent intent)
Call startActivity from the fragment's containing Activity.
startActivity
public void startActivity(@NonNull Intent intent, @Nullable Bundle options)
Call startActivity from the fragment's containing Activity.
public voidstartActivityForResult(@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 |
public voidstartActivityForResult(
@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 |
@Nullable Bundle options |
Additional options for how the Activity should be started. See |
public voidstartIntentSenderForResult(
@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 |
@Nullable Intent fillInIntent |
If non-null, this will be provided as the intent parameter to |
int flagsMask |
Intent flags in the original IntentSender that you would like to change. |
int flagsValues |
Desired values for any bits set in |
int extraFlags |
Always set to 0. |
@Nullable Bundle options |
Additional options for how the Activity should be started. See |
startPostponedEnterTransition
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.
| See also | |
|---|---|
startPostponedEnterTransition |
unregisterForContextMenu
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.
| See also | |
|---|---|
registerForContextMenu |
Extension functions
AuthenticationUtils.registerForAuthenticationResult
public final @NonNull AuthenticationResultLauncher AuthenticationUtils.registerForAuthenticationResult(
@NonNull Fragment receiver,
@NonNull AuthenticationResultCallback resultCallback
)
Returns an AuthenticationResultLauncher that can be used to initiate authentication.
A success or error result will be delivered to AuthenticationResultCallback.onAuthResult and (one or more) failures will be delivered to AuthenticationResultCallback.onAuthAttemptFailed, which is set by resultCallback. The callback will be executed on the main thread.
This must be called unconditionally, as part of initialization path, typically as a field initializer of an Fragment.
Note that if multiple calls to this method are made within a single Fragment or Activity, only the callback registered by the last invocation will be saved and receive authentication results. This can result in unexpected behavior if you intend to manage multiple independent authentication flows. It is strongly recommended to avoid multiple calls to this method in such scenarios.
import androidx.biometric.AuthenticationRequest import androidx.biometric.AuthenticationRequest.Biometric import androidx.biometric.AuthenticationRequest.Companion.biometricRequest import androidx.biometric.AuthenticationResult import androidx.biometric.PromptContentItemBulletedText import androidx.biometric.registerForAuthenticationResult import androidx.fragment.app.Fragment class MyFragmentForCredentialOnlyAuth : Fragment() { val requestAuthentication = registerForAuthenticationResult { result: AuthenticationResult -> when (result) { // Handle successful authentication is AuthenticationResult.Success -> { Log.i(TAG, "onAuthenticationSucceeded with type ${result.authType}") } // Handle authentication error, e.g. user cancellation, lockout errors, etc is AuthenticationResult.Error -> { Log.i( TAG, "onAuthenticationError " + "with error code: ${result.errorCode} " + "and error string: ${result.errString}", ) } // Handle fallback option clicks is AuthenticationResult.CustomFallbackSelected -> { Log.i(TAG, "fallback is selected, text: ${result.fallback.text}") } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val authRequest = biometricRequest(title = "Title", Biometric.Fallback.DeviceCredential) { setSubtitle("Subtitle") setContent( AuthenticationRequest.BodyContent.VerticalList( "Vertical list description", listOf( PromptContentItemBulletedText("test item1"), PromptContentItemBulletedText("test item2"), ), ) ) setMinStrength(Biometric.Strength.Class3(/*optional: cryptoObject*/ )) setIsConfirmationRequired(true) } Button(context).setOnClickListener { requestAuthentication.launch(authRequest) } } }
| See also | |
|---|---|
registerForAuthenticationResult |
(Executor, AuthenticationResultCallback) |
AuthenticationUtils.registerForAuthenticationResult
public final @NonNull AuthenticationResultLauncher AuthenticationUtils.registerForAuthenticationResult(
@NonNull Fragment receiver,
@NonNull Executor callbackExecutor,
@NonNull AuthenticationResultCallback resultCallback
)
Returns an AuthenticationResultLauncher that can be used to initiate authentication.
A success or error result will be delivered to AuthenticationResultCallback.onAuthResult and (one or more) failures will be delivered to AuthenticationResultCallback.onAuthAttemptFailed, which is set by resultCallback. The callback will be executed on the thread provided by the callbackExecutor.
This must be called unconditionally, as part of initialization path, typically as a field initializer of an Fragment.
Note that if multiple calls to this method are made within a single Fragment or Activity, only the callback registered by the last invocation will be saved and receive authentication results. This can result in unexpected behavior if you intend to manage multiple independent authentication flows. It is strongly recommended to avoid multiple calls to this method in such scenarios.
import androidx.biometric.AuthenticationRequest import androidx.biometric.AuthenticationRequest.Biometric import androidx.biometric.AuthenticationRequest.Companion.biometricRequest import androidx.biometric.AuthenticationResult import androidx.biometric.PromptContentItemBulletedText import androidx.biometric.registerForAuthenticationResult import androidx.fragment.app.Fragment class MyFragmentForCredentialOnlyAuth : Fragment() { val requestAuthentication = registerForAuthenticationResult { result: AuthenticationResult -> when (result) { // Handle successful authentication is AuthenticationResult.Success -> { Log.i(TAG, "onAuthenticationSucceeded with type ${result.authType}") } // Handle authentication error, e.g. user cancellation, lockout errors, etc is AuthenticationResult.Error -> { Log.i( TAG, "onAuthenticationError " + "with error code: ${result.errorCode} " + "and error string: ${result.errString}", ) } // Handle fallback option clicks is AuthenticationResult.CustomFallbackSelected -> { Log.i(TAG, "fallback is selected, text: ${result.fallback.text}") } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val authRequest = biometricRequest(title = "Title", Biometric.Fallback.DeviceCredential) { setSubtitle("Subtitle") setContent( AuthenticationRequest.BodyContent.VerticalList( "Vertical list description", listOf( PromptContentItemBulletedText("test item1"), PromptContentItemBulletedText("test item2"), ), ) ) setMinStrength(Biometric.Strength.Class3(/*optional: cryptoObject*/ )) setIsConfirmationRequired(true) } Button(context).setOnClickListener { requestAuthentication.launch(authRequest) } } }
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.
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.
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.
FragmentKt.setFragmentResultListener
public final void FragmentKt.setFragmentResultListener(
@NonNull Fragment receiver,
@NonNull String requestKey,
@NonNull Function2<@NonNull String, @NonNull Bundle, Unit> 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.
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 the default factory.
This method also takes a CreationExtras producer that provides default extras to the created ViewModel.
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 androidx.navigation.NavController back stack:
class MyFragment : Fragment() {
val viewmodel: MainViewModel by hiltNavGraphViewModels(R.navigation.main)
}
This property can be accessed only after this NavGraph is on the NavController back stack, and an attempt access prior to that will result in an IllegalArgumentException.
| Parameters | |
|---|---|
@IdRes int navGraphId |
ID of a NavGraph that exists on the |
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 androidx.navigation.NavController back stack:
class MyFragment : Fragment() {
val viewmodel: MainViewModel by hiltNavGraphViewModels(R.navigation.main) { factory: MainViewModelFactory ->
factory.create(...)
}
}
This property can be accessed only after this NavGraph is on the NavController back stack, and an attempt access prior to that will result in an IllegalArgumentException.
| Parameters | |
|---|---|
@IdRes int navGraphId |
ID of a NavGraph that exists on the |
@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 |
Function0<@NonNull CreationExtras> extrasProducer |
lambda that will be called during initialization to return |
Function0<@NonNull ViewModelProvider.Factory> factoryProducer |
lambda that will be called during initialization to return |
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 |
|
Function0<@NonNull CreationExtras> extrasProducer |
lambda that will be called during initialization to return |
Function0<@NonNull ViewModelProvider.Factory> factoryProducer |
lambda that will be called during initialization to return |