{% setvar book_path %}/reference/kotlin/androidx/_book.yaml{% endsetvar %} {% include "_shared/_reference-head-tags.html" %}

Fragment

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

Known direct subclasses
DialogFragment

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

ListFragment

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


Static library support version of the framework's android.app.Fragment. Used to write apps that run on platforms prior to Android 3.0. When running on Android 3.0 or above, this implementation is still used; it does not try to switch to the framework's implementation. See the framework android.app.Fragment documentation for a class overview.

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

Summary

Nested types

class Fragment.InstantiationException : RuntimeException

Thrown by instantiate when there is an instantiation failure.

class Fragment.SavedState : Parcelable

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

Public constructors

Constructor used by the default FragmentFactory.

@ContentView
Fragment(contentLayoutId: @LayoutRes Int)

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

Public functions

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

Print the Fragments's state into the given stream.

Boolean
equals(o: Any?)

Subclasses can not override equals().

FragmentActivity?

Return the FragmentActivity this fragment is currently associated with.

Boolean

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

Boolean

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

Bundle?

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

FragmentManager

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

Context?

Return the Context this fragment is currently associated with.

CreationExtras

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.

ViewModelProvider.Factory
Any?

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

Any?

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

FragmentManager?

This function is deprecated.

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

Any?

Return the host object of this fragment.

Int

Return the identifier this fragment is known by.

LayoutInflater

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

Lifecycle

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

LoaderManager

This function is deprecated.

Use LoaderManager.getInstance(this).

Fragment?

Returns the parent Fragment containing this Fragment.

FragmentManager

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

Any?

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

Resources

Return requireActivity().getResources().

Boolean

This function is deprecated.

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

Any?

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

SavedStateRegistry
Any?

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

Any?

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

String
getString(resId: @StringRes Int, formatArgs: Array<Any!>?)

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

String

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

String?

Get the tag name of the fragment, if specified.

Fragment?

This function is deprecated.

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

Int

This function is deprecated.

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

CharSequence

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

Boolean

This function is deprecated.

Use setMaxLifecycle instead.

View?

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

LifecycleOwner

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

LiveData<LifecycleOwner!>

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

ViewModelStore

Returns the ViewModelStore associated with this Fragment

Int

Subclasses can not override hashCode().

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

This function is deprecated.

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

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

This function is deprecated.

Use getFragmentFactory and instantiate

Boolean

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

Boolean

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

Boolean

Return true if the fragment has been hidden.

Boolean

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

Boolean

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

Boolean

Return true if the fragment is in the resumed state.

Boolean

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

Boolean

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

Unit

This function is deprecated.

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

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

This function is deprecated.

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

Unit

This function is deprecated.

See onAttach.

Unit

Called when a fragment is first attached to its context.

Unit

This function is deprecated.

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

Unit
Boolean

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

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

Called to do initial creation of a fragment.

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

Called when a fragment loads an animation.

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

Called when a fragment loads an animator.

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

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

Unit

This function is deprecated.

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

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

Called to have the fragment instantiate its user interface view.

Unit

Called when the fragment is no longer in use.

Unit

This function is deprecated.

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

Unit

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

Unit

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

LayoutInflater
onGetLayoutInflater(savedInstanceState: Bundle?)

Returns the LayoutInflater used to inflate Views of this Fragment.

Unit

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

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

This function is deprecated.

See onInflate.

Unit
@UiThread
@CallSuper
onInflate(
    context: Context,
    attrs: AttributeSet,
    savedInstanceState: Bundle?
)

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

Unit
Unit
onMultiWindowModeChanged(isInMultiWindowMode: Boolean)

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

Boolean

This function is deprecated.

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

Unit

This function is deprecated.

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

Unit

Called when the Fragment is no longer resumed.

Unit
onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean)

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

Unit

This function is deprecated.

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

Unit
@MainThread
onPrimaryNavigationFragmentChanged(
    isPrimaryNavigationFragment: Boolean
)

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

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

This function is deprecated.

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

Unit

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

Unit

Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance if its process is restarted.

Unit

Called when the Fragment is visible to the user.

Unit

Called when the Fragment is no longer started.

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

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

Unit

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

Unit

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

Unit
postponeEnterTransition(duration: Long, timeUnit: TimeUnit)

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

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

If the host of this fragment is an ActivityResultRegistryOwner the ActivityResultRegistry of the host will be used.

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

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

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

This function is deprecated.

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

FragmentActivity

Return the FragmentActivity this fragment is currently associated with.

Bundle

Return the arguments supplied when the fragment was instantiated.

Context

Return the Context this fragment is currently associated with.

FragmentManager

This function is deprecated.

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

Any

Return the host object of this fragment.

Fragment

Returns the parent Fragment containing this Fragment.

View

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

Unit

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

Unit

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

Unit

Supply the construction arguments for this fragment.

Unit

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

Unit
setEnterTransition(transition: Any?)

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

Unit

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

Unit
setExitTransition(transition: Any?)

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

Unit

This function is deprecated.

This method is no longer needed when using a MenuProvider to provide a Menu to your activity, which replaces onCreateOptionsMenu as the recommended way to provide a consistent, optionally Lifecycle-aware, and modular way to handle menu creation and item selection.

Unit

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

Unit
setMenuVisibility(menuVisible: Boolean)

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

Unit
setReenterTransition(transition: Any?)

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

Unit

This function is deprecated.

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

Unit
setReturnTransition(transition: Any?)

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

Unit

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

Unit

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

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

This function is deprecated.

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

Unit
setUserVisibleHint(isVisibleToUser: Boolean)

This function is deprecated.

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

Boolean

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

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

Call startActivity from the fragment's containing Activity.

Unit

Call startActivity from the fragment's containing Activity.

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

This function is deprecated.

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

Unit
startActivityForResult(intent: Intent!, requestCode: Int)

This function is deprecated.

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

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

This function is deprecated.

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

Unit

Begin postponed transitions after postponeEnterTransition was called.

String
Unit

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

Public constructors

Fragment

Fragment()

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

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

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

Fragment

@ContentView
Fragment(contentLayoutId: @LayoutRes Int)

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

class MyFragment extends Fragment {
  public MyFragment() {
    super(R.layout.fragment_main);
  }
}
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.
See also
Fragment
onCreateView

Public functions

dump

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

Print the Fragments's state into the given stream.

Parameters
prefix: String

Text to print at the front of each line.

fd: FileDescriptor?

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

writer: PrintWriter

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

args: Array<String!>?

additional arguments to the dump request.

equals

fun equals(o: Any?): Boolean

Subclasses can not override equals().

getActivity

fun getActivity(): FragmentActivity?

Return the FragmentActivity this fragment is currently associated with. May return null if the fragment is associated with a Context instead.

See also
requireActivity

getAllowEnterTransitionOverlap

fun getAllowEnterTransitionOverlap(): Boolean

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

Returns
Boolean

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

getAllowReturnTransitionOverlap

fun getAllowReturnTransitionOverlap(): Boolean

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

Returns
Boolean

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

getArguments

fun getArguments(): Bundle?

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

getChildFragmentManager

fun getChildFragmentManager(): FragmentManager

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

getContext

fun getContext(): Context?

Return the Context this fragment is currently associated with.

See also
requireContext

getDefaultViewModelCreationExtras

@CallSuper
fun getDefaultViewModelCreationExtras(): CreationExtras

The Fragment's arguments when this is first called will be used as the defaults to any androidx.lifecycle.SavedStateHandle passed to a view model created using this extra.

getDefaultViewModelProviderFactory

fun getDefaultViewModelProviderFactory(): ViewModelProvider.Factory

getEnterTransition

fun getEnterTransition(): Any?

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

Returns
Any?

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

getExitTransition

fun getExitTransition(): Any?

Returns the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack. The exiting Views will be those that are regular Views or ViewGroups that have isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as exiting is governed by changing visibility from VISIBLE to INVISIBLE. If transition is null, the views will remain unaffected.

Returns
Any?

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

getFragmentManager

fun getFragmentManager(): FragmentManager?

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

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

See also
getParentFragmentManager

getHost

fun getHost(): Any?

Return the host object of this fragment. May return null if the fragment isn't currently being hosted.

See also
requireHost

getId

fun getId(): Int

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

getLayoutInflater

fun getLayoutInflater(): LayoutInflater

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

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

Returns
LayoutInflater

The LayoutInflater used to inflate Views of this Fragment.

getLifecycle

fun getLifecycle(): Lifecycle

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

getLoaderManager

fun getLoaderManager(): LoaderManager

Return the LoaderManager for this fragment.

getParentFragment

fun getParentFragment(): Fragment?

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

getParentFragmentManager

fun getParentFragmentManager(): FragmentManager

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

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

Throws
java.lang.IllegalStateException: java.lang.IllegalStateException

if not associated with a transaction or host.

getReenterTransition

fun getReenterTransition(): Any?

Returns the Transition that will be used to move Views in to the scene when returning due to popping a back stack. The entering Views will be those that are regular Views or ViewGroups that have isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as exiting is governed by changing visibility from VISIBLE to INVISIBLE. If nothing is set, the default will be to use the same transition as getExitTransition.

Returns
Any?

the Transition to use to move Views into the scene when reentering from a previously-started Activity due to popping the back stack.

getResources

fun getResources(): Resources

Return requireActivity().getResources().

getRetainInstance

fun getRetainInstance(): Boolean

Returns true if this fragment instance's state will be retained across configuration changes, and false if it will not.

Returns
Boolean

whether or not this fragment instance will be retained.

See also
setRetainInstance

getReturnTransition

fun getReturnTransition(): Any?

Returns the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack. The exiting Views will be those that are regular Views or ViewGroups that have isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as entering is governed by changing visibility from VISIBLE to INVISIBLE. If nothing is set, the default will be to use the same transition as getEnterTransition.

Returns
Any?

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

getSavedStateRegistry

fun getSavedStateRegistry(): SavedStateRegistry

getSharedElementEnterTransition

fun getSharedElementEnterTransition(): Any?

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

Returns
Any?

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

getSharedElementReturnTransition

fun getSharedElementReturnTransition(): Any?

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

Returns
Any?

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

getString

fun getString(resId: @StringRes Int, formatArgs: Array<Any!>?): String

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

Parameters
resId: @StringRes Int

Resource id for the format string

formatArgs: Array<Any!>?

The format arguments that will be used for substitution.

getString

fun getString(resId: @StringRes Int): String

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

Parameters
resId: @StringRes Int

Resource id for the string

getTag

fun getTag(): String?

Get the tag name of the fragment, if specified.

getTargetFragment

fun getTargetFragment(): Fragment?

Return the target fragment set by setTargetFragment.

getTargetRequestCode

fun getTargetRequestCode(): Int

Return the target request code set by setTargetFragment.

getText

fun getText(resId: @StringRes Int): CharSequence

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

Parameters
resId: @StringRes Int

Resource id for the CharSequence text

getUserVisibleHint

fun getUserVisibleHint(): Boolean
Returns
Boolean

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

See also
setUserVisibleHint

getView

fun getView(): View?

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

Returns
View?

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

getViewLifecycleOwner

@MainThread
fun getViewLifecycleOwner(): LifecycleOwner

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

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

  1. created after onViewStateRestored
  2. started after onStart
  3. resumed after onResume
  4. paused before onPause
  5. stopped before onStop
  6. destroyed before onDestroyView
The first method where it is safe to access the view lifecycle is onCreateView under the condition that you must return a non-null view (an IllegalStateException will be thrown if you access the view lifecycle but don't return a non-null view).

The view lifecycle remains valid through the call to onDestroyView, after which getView will return null, the view lifecycle will be destroyed, and this method will throw an IllegalStateException. Consider using getViewLifecycleOwnerLiveData or runOnCommit to receive a callback for when the Fragment's view lifecycle is available.

This should only be called on the main thread.

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

Returns
LifecycleOwner

A LifecycleOwner that represents the Fragment's View lifecycle.

Throws
java.lang.IllegalStateException: java.lang.IllegalStateException

if the Fragment's View is null.

getViewLifecycleOwnerLiveData

fun getViewLifecycleOwnerLiveData(): LiveData<LifecycleOwner!>

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

This will be set to the new LifecycleOwner after onCreateView returns a non-null View and will set to null after onDestroyView.

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

Returns
LiveData<LifecycleOwner!>

A LiveData that changes in sync with getViewLifecycleOwner.

getViewModelStore

fun getViewModelStore(): ViewModelStore

Returns the ViewModelStore associated with this Fragment

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

Returns
ViewModelStore

a ViewModelStore

Throws
java.lang.IllegalStateException: java.lang.IllegalStateException

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

hashCode

fun hashCode(): Int

Subclasses can not override hashCode().

instantiate

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

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

Parameters
context: Context

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

fname: String

The class name of the fragment to instantiate.

args: Bundle?

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

Returns
Fragment

Returns a new fragment instance.

Throws
androidx.fragment.app.Fragment.InstantiationException: 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.

instantiate

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

Like instantiate but with a null argument Bundle.

isAdded

fun isAdded(): Boolean

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

isDetached

fun isDetached(): Boolean

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

isHidden

fun isHidden(): Boolean

Return true if the fragment has been hidden. This includes the case if the fragment is hidden because its parent is hidden. By default fragments are shown. You can find out about changes to this state with onHiddenChanged. Note that the hidden state is orthogonal to other states -- that is, to be visible to the user, a fragment must be both started and not hidden.

isInLayout

fun isInLayout(): Boolean

Return true if the layout is included as part of an activity view hierarchy via the 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

fun isRemoving(): Boolean

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

isResumed

fun isResumed(): Boolean

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

isStateSaved

fun isStateSaved(): Boolean

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

Returns
Boolean

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

isVisible

fun isVisible(): Boolean

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

onActivityCreated

@MainThread
@CallSuper
fun onActivityCreated(savedInstanceState: Bundle?): Unit

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

Parameters
savedInstanceState: Bundle?

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

onActivityResult

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

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

Parameters
requestCode: Int

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

resultCode: Int

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

data: Intent?

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

onAttach

@MainThread
@CallSuper
fun onAttach(activity: Activity): Unit

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

onAttach

@MainThread
@CallSuper
fun onAttach(context: Context): Unit

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

onAttachFragment

@MainThread
fun onAttachFragment(childFragment: Fragment): Unit

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

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

Parameters
childFragment: Fragment

child fragment being attached

onConfigurationChanged

@CallSuper
fun onConfigurationChanged(newConfig: Configuration): Unit

onContextItemSelected

@MainThread
fun onContextItemSelected(item: MenuItem): Boolean

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

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

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

Parameters
item: MenuItem

The context menu item that was selected.

Returns
Boolean

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

onCreate

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

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

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

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

Parameters
savedInstanceState: Bundle?

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

onCreateAnimation

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

Called when a fragment loads an animation. Note that if setCustomAnimations was called with Animator resources instead of Animation resources, nextAnim will be an animator resource.

Parameters
transit: Int

The value set in setTransition or 0 if not set.

enter: Boolean

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

nextAnim: Int

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

onCreateAnimator

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

Called when a fragment loads an animator. This will be called when onCreateAnimation returns null. Note that if setCustomAnimations was called with Animation resources instead of Animator resources, nextAnim will be an animation resource.

Parameters
transit: Int

The value set in setTransition or 0 if not set.

enter: Boolean

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

nextAnim: Int

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

onCreateContextMenu

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

Called when a context menu for the view is about to be shown. Unlike onCreateOptionsMenu, this will be called every time the context menu is about to be shown and should be populated for the view (or item inside the view for AdapterView subclasses, this can be found in the menuInfo)).

Use onContextItemSelected to know when an item has been selected.

The default implementation calls up to Activity.onCreateContextMenu, though you can not call this implementation if you don't want that behavior.

It is not safe to hold onto the context menu after this method returns.

onCreateOptionsMenu

@MainThread
fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater): Unit

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

Parameters
menu: Menu

The options menu in which you place your items.

See also
setHasOptionsMenu
onPrepareOptionsMenu
onOptionsItemSelected

onCreateView

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

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

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

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

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

Parameters
inflater: LayoutInflater

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

container: ViewGroup?

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

savedInstanceState: Bundle?

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

Returns
View?

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

onDestroy

@MainThread
@CallSuper
fun onDestroy(): Unit

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

onDestroyOptionsMenu

@MainThread
fun onDestroyOptionsMenu(): Unit

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

onDestroyView

@MainThread
@CallSuper
fun onDestroyView(): Unit

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

onDetach

@MainThread
@CallSuper
fun onDetach(): Unit

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

onGetLayoutInflater

fun onGetLayoutInflater(savedInstanceState: Bundle?): LayoutInflater

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

Parameters
savedInstanceState: Bundle?

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

Returns
LayoutInflater

The LayoutInflater used to inflate Views of this Fragment.

onHiddenChanged

@MainThread
fun onHiddenChanged(hidden: Boolean): Unit

Called when the hidden state (as returned by isHidden of the fragment or another fragment in its hierarchy has changed. Fragments start out not hidden; this will be called whenever the fragment changes state from that.

Parameters
hidden: Boolean

True if the fragment is now hidden, false otherwise.

onInflate

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

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

onInflate

@UiThread
@CallSuper
fun onInflate(
    context: Context,
    attrs: AttributeSet,
    savedInstanceState: Bundle?
): Unit

Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity. This may be called immediately after the fragment is created from a FragmentContainerView in a layout file. Note this is before the fragment's onAttach has been called; all you should do here is parse the attributes and save them away.

This is called the first time the fragment is inflated. If it is being inflated into a new instance with saved state, this method will not be called a second time for the restored state fragment.

Here is a typical implementation of a fragment that can take parameters both through attributes supplied here as well from getArguments:

public static class MyFragment extends Fragment {
    CharSequence mLabel;

    /**
     * Create a new instance of MyFragment that will be initialized
     * with the given arguments.
     */
    static MyFragment newInstance(CharSequence label) {
        MyFragment f = new MyFragment();
        Bundle b = new Bundle();
        b.putCharSequence("label", label);
        f.setArguments(b);
        return f;
    }

    /**
     * Parse attributes during inflation from a view hierarchy into the
     * arguments we handle.
     */
    @Override
    public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs,
                          @Nullable Bundle savedInstanceState) {
        super.onInflate(context, attrs, savedInstanceState);

        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.FragmentArguments);
        mLabel = a.getText(R.styleable.FragmentArguments_android_label);
        a.recycle();
    }

    /**
     * During creation, if arguments have been supplied to the fragment
     * then parse those out.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle args = getArguments();
        if (args != null) {
            CharSequence label = args.getCharSequence("label");
            if (label != null) {
                mLabel = label;
            }
        }
    }

    /**
     * Create the view for this fragment, using the arguments given to it.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.hello_world, container, false);
        View tv = v.findViewById(R.id.text);
        ((TextView)tv).setText(mLabel != null ? mLabel : "(no label)");
        ViewCompat.setBackground(
                tv, ContextCompat.getDrawable(getContext(), android.R.drawable.gallery_thumb));
        return v;
    }
}

Note that parsing the XML attributes uses a "styleable" resource. The declaration for the styleable used here is:

<declare-styleable name="FragmentArguments">
    <attr name="android:label" />
</declare-styleable>

The fragment can then be declared within its activity's content layout through a tag like this:

<androidx.fragment.app.FragmentContainerView
        class="com.example.android.supportv4.app.FragmentArgumentsSupport$MyFragment"
        android:id="@+id/embedded"
        android:layout_width="0px" android:layout_height="wrap_content"
        android:layout_weight="1"
        android:label="@string/fragment_arguments_embedded" />

This fragment can also be created dynamically from arguments given at runtime in the arguments Bundle; here is an example of doing so at creation of the containing activity:

@Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_arguments_support);

    if (savedInstanceState == null) {
        // First-time init; create fragment to embed in activity.
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment newFragment = MyFragment.newInstance("From Arguments");
        ft.add(R.id.created, newFragment);
        ft.commit();
    }
}
Parameters
context: Context

The Activity that is inflating this fragment.

attrs: AttributeSet

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

savedInstanceState: Bundle?

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

onLowMemory

@MainThread
@CallSuper
fun onLowMemory(): Unit

onMultiWindowModeChanged

fun onMultiWindowModeChanged(isInMultiWindowMode: Boolean): Unit

Called when the Fragment's activity changes from fullscreen mode to multi-window mode and visa-versa. This is generally tied to onMultiWindowModeChanged of the containing Activity.

Parameters
isInMultiWindowMode: Boolean

True if the activity is in multi-window mode.

onOptionsItemSelected

@MainThread
fun onOptionsItemSelected(item: MenuItem): Boolean

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

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

Parameters
item: MenuItem

The menu item that was selected.

Returns
Boolean

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

See also
onCreateOptionsMenu

onOptionsMenuClosed

@MainThread
fun onOptionsMenuClosed(menu: Menu): Unit

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

Parameters
menu: Menu

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

onPause

@MainThread
@CallSuper
fun onPause(): Unit

Called when the Fragment is no longer resumed. This is generally tied to Activity.onPause of the containing Activity's lifecycle.

onPictureInPictureModeChanged

fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean): Unit

Called by the system when the activity changes to and from picture-in-picture mode. This is generally tied to onPictureInPictureModeChanged of the containing Activity.

Parameters
isInPictureInPictureMode: Boolean

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

onPrepareOptionsMenu

@MainThread
fun onPrepareOptionsMenu(menu: Menu): Unit

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

Parameters
menu: Menu

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

See also
setHasOptionsMenu
onCreateOptionsMenu

onPrimaryNavigationFragmentChanged

@MainThread
fun onPrimaryNavigationFragmentChanged(
    isPrimaryNavigationFragment: Boolean
): Unit

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

Parameters
isPrimaryNavigationFragment: Boolean

True if and only if this Fragment and any parent fragment is set as the primary navigation fragment via setPrimaryNavigationFragment.

onRequestPermissionsResult

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

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

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

Parameters
requestCode: Int

The request code passed in requestPermissions.

permissions: Array<String!>

The requested permissions. Never null.

grantResults: IntArray

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

See also
requestPermissions

onResume

@MainThread
@CallSuper
fun onResume(): Unit

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

onSaveInstanceState

@MainThread
fun onSaveInstanceState(outState: Bundle): Unit

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

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

Parameters
outState: Bundle

Bundle in which to place your saved state.

onStart

@MainThread
@CallSuper
fun onStart(): Unit

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

onStop

@MainThread
@CallSuper
fun onStop(): Unit

Called when the Fragment is no longer started. This is generally tied to Activity.onStop of the containing Activity's lifecycle.

onViewCreated

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

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

Parameters
view: View

The View returned by onCreateView.

savedInstanceState: Bundle?

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

onViewStateRestored

@MainThread
@CallSuper
fun onViewStateRestored(savedInstanceState: Bundle?): Unit

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

Parameters
savedInstanceState: Bundle?

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

postponeEnterTransition

fun postponeEnterTransition(): Unit

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

This method gives the Fragment the ability to delay Fragment animations until all data is loaded. Until then, the added, shown, and attached Fragments will be INVISIBLE and removed, hidden, and detached Fragments won't be have their Views removed. The transaction runs when all postponed added Fragments in the transaction have called startPostponedEnterTransition.

This method should be called before being added to the FragmentTransaction or in onCreate, onAttach, or onCreateView}. startPostponedEnterTransition must be called to allow the Fragment to start the transitions.

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

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

See also
postponeEnterTransition
setReorderingAllowed

postponeEnterTransition

fun postponeEnterTransition(duration: Long, timeUnit: TimeUnit): Unit

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

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

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

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

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

Parameters
duration: Long

The length of the delay in timeUnit units

timeUnit: TimeUnit

The units of time for duration

See also
postponeEnterTransition
setReorderingAllowed

registerForActivityResult

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

If the host of this fragment is an ActivityResultRegistryOwner the ActivityResultRegistry of the host will be used. Otherwise, this will use the registry of the Fragment's Activity.

registerForActivityResult

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

registerForContextMenu

fun registerForContextMenu(view: View): Unit

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

Parameters
view: View

The view that should show a context menu.

See also
unregisterForContextMenu

requestPermissions

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

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

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

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

If your app does not have the requested permissions the user will be presented with UI for accepting them. After the user has accepted or rejected the requested permissions you will receive a callback on onRequestPermissionsResult reporting whether the permissions were granted or not.

Note that requesting a permission does not guarantee it will be granted and your app should be able to run without having this permission.

This method may start an activity allowing the user to choose which permissions to grant and which to reject. Hence, you should be prepared that your activity may be paused and resumed. Further, granting some permissions may require a restart of you application. In such a case, the system will recreate the activity stack before delivering the result to onRequestPermissionsResult.

When checking whether you have a permission you should use checkSelfPermission.

Calling this API for permissions already granted to your app would show UI to the user to decided whether the app can still hold these permissions. This can be useful if the way your app uses the data guarded by the permissions changes significantly.

Parameters
permissions: Array<String!>

The requested permissions.

requestCode: Int

Application specific request code to match with a result reported to onRequestPermissionsResult. Must be between 0 and 65535 to be considered valid. If given requestCode is greater than 65535, an IllegalArgumentException would be thrown.

See also
onRequestPermissionsResult
checkSelfPermission

requireActivity

fun requireActivity(): FragmentActivity

Return the FragmentActivity this fragment is currently associated with.

Throws
java.lang.IllegalStateException: java.lang.IllegalStateException

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

See also
getActivity

requireArguments

fun requireArguments(): Bundle

Return the arguments supplied when the fragment was instantiated.

Throws
java.lang.IllegalStateException: java.lang.IllegalStateException

if no arguments were supplied to the Fragment.

See also
getArguments

requireContext

fun requireContext(): Context

Return the Context this fragment is currently associated with.

Throws
java.lang.IllegalStateException: java.lang.IllegalStateException

if not currently associated with a context.

See also
getContext

requireFragmentManager

fun requireFragmentManager(): FragmentManager

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

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

Throws
java.lang.IllegalStateException: java.lang.IllegalStateException

if not associated with a transaction or host.

See also
getParentFragmentManager

requireHost

fun requireHost(): Any

Return the host object of this fragment.

Throws
java.lang.IllegalStateException: java.lang.IllegalStateException

if not currently associated with a host.

See also
getHost

requireParentFragment

fun requireParentFragment(): Fragment

Returns the parent Fragment containing this Fragment.

Throws
java.lang.IllegalStateException: java.lang.IllegalStateException

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

See also
getParentFragment

requireView

fun requireView(): View

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

Throws
java.lang.IllegalStateException: java.lang.IllegalStateException

if no view was returned by onCreateView.

See also
getView

setAllowEnterTransitionOverlap

fun setAllowEnterTransitionOverlap(allow: Boolean): Unit

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

Parameters
allow: Boolean

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

setAllowReturnTransitionOverlap

fun setAllowReturnTransitionOverlap(allow: Boolean): Unit

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

Parameters
allow: Boolean

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

setArguments

fun setArguments(args: Bundle?): Unit

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

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

setEnterSharedElementCallback

fun setEnterSharedElementCallback(callback: SharedElementCallback?): Unit

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

Parameters
callback: SharedElementCallback?

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

setEnterTransition

fun setEnterTransition(transition: Any?): Unit

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

Parameters
transition: Any?

The Transition to use to move Views into the initial Scene. transition must be an android.transition.Transition or androidx.transition.Transition.

setExitSharedElementCallback

fun setExitSharedElementCallback(callback: SharedElementCallback?): Unit

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

Parameters
callback: SharedElementCallback?

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

setExitTransition

fun setExitTransition(transition: Any?): Unit

Sets the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack. The exiting Views will be those that are regular Views or ViewGroups that have isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as exiting is governed by changing visibility from VISIBLE to INVISIBLE. If transition is null, the views will remain unaffected.

Parameters
transition: Any?

The Transition to use to move Views out of the Scene when the Fragment is being closed not due to popping the back stack. transitionmust be an android.transition.Transition or androidx.transition.Transition.

setHasOptionsMenu

fun setHasOptionsMenu(hasMenu: Boolean): Unit

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

Parameters
hasMenu: Boolean

If true, the fragment has menu items to contribute.

setInitialSavedState

fun setInitialSavedState(state: Fragment.SavedState?): Unit

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

Parameters
state: Fragment.SavedState?

The state the fragment should be restored from.

setMenuVisibility

fun setMenuVisibility(menuVisible: Boolean): Unit

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

Parameters
menuVisible: Boolean

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

setReenterTransition

fun setReenterTransition(transition: Any?): Unit

Sets the Transition that will be used to move Views in to the scene when returning due to popping a back stack. The entering Views will be those that are regular Views or ViewGroups that have isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as exiting is governed by changing visibility from VISIBLE to INVISIBLE. If transition is null, the views will remain unaffected. If nothing is set, the default will be to use the same transition as getExitTransition.

Parameters
transition: Any?

The Transition to use to move Views into the scene when reentering from a previously-started Activity due to popping the back stack. transitionmust be an android.transition.Transition or androidx.transition.Transition.

setRetainInstance

fun setRetainInstance(retain: Boolean): Unit

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

Parameters
retain: Boolean

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

See also
getRetainInstance

setReturnTransition

fun setReturnTransition(transition: Any?): Unit

Sets the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack. The exiting Views will be those that are regular Views or ViewGroups that have isTransitionGroup return true. Typical Transitions will extend android.transition.Visibility as entering is governed by changing visibility from VISIBLE to INVISIBLE. If transition is null, entering Views will remain unaffected. If nothing is set, the default will be to use the same value as set in setEnterTransition.

Parameters
transition: Any?

The Transition to use to move Views out of the Scene when the Fragment is preparing to close due to popping the back stack. transition must be an android.transition.Transition or androidx.transition.Transition.

setSharedElementEnterTransition

fun setSharedElementEnterTransition(transition: Any?): Unit

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

Parameters
transition: Any?

The Transition to use for shared elements transferred into the content Scene. transition must be an android.transition.Transition or androidx.transition.Transition.

setSharedElementReturnTransition

fun setSharedElementReturnTransition(transition: Any?): Unit

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

Parameters
transition: Any?

The Transition to use for shared elements transferred out of the content Scene. transition must be an android.transition.Transition or androidx.transition.Transition.

setTargetFragment

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

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

Parameters
fragment: Fragment?

The fragment that is the target of this one.

requestCode: Int

Optional request code, for convenience if you are going to call back with onActivityResult.

setUserVisibleHint

fun setUserVisibleHint(isVisibleToUser: Boolean): Unit

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

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

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

Parameters
isVisibleToUser: Boolean

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

shouldShowRequestPermissionRationale

fun shouldShowRequestPermissionRationale(permission: String): Boolean

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

Parameters
permission: String

A permission your app wants to request.

Returns
Boolean

Whether you should show permission rationale UI.

See also
checkSelfPermission
requestPermissions
onRequestPermissionsResult

startActivity

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

Call startActivity from the fragment's containing Activity.

startActivity

fun startActivity(intent: Intent!): Unit

Call startActivity from the fragment's containing Activity.

startActivityForResult

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

Call startActivityForResult from the fragment's containing Activity.

Parameters
intent: Intent!

The intent to start.

requestCode: Int

The request code to be returned in onActivityResult when the activity exits. Must be between 0 and 65535 to be considered valid. If given requestCode is greater than 65535, an IllegalArgumentException would be thrown.

options: Bundle?

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

startActivityForResult

fun startActivityForResult(intent: Intent!, requestCode: Int): Unit

Call startActivityForResult from the fragment's containing Activity.

Parameters
intent: Intent!

The intent to start.

requestCode: Int

The request code to be returned in onActivityResult when the activity exits. Must be between 0 and 65535 to be considered valid. If given requestCode is greater than 65535, an IllegalArgumentException would be thrown.

startIntentSenderForResult

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

Call startIntentSenderForResult from the fragment's containing Activity.

Parameters
intent: IntentSender!

The IntentSender to launch.

requestCode: Int

The request code to be returned in onActivityResult when the activity exits. Must be between 0 and 65535 to be considered valid. If given requestCode is greater than 65535, an IllegalArgumentException would be thrown.

fillInIntent: Intent?

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

flagsMask: Int

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

flagsValues: Int

Desired values for any bits set in flagsMask.

extraFlags: Int

Always set to 0.

options: Bundle?

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

Throws
android.content.IntentSender.SendIntentException: android.content.IntentSender.SendIntentException

startPostponedEnterTransition

fun startPostponedEnterTransition(): Unit

Begin postponed transitions after postponeEnterTransition was called. If postponeEnterTransition() was called, you must call startPostponedEnterTransition() or executePendingTransactions to complete the FragmentTransaction. If postponement was interrupted with executePendingTransactions, before startPostponedEnterTransition(), animations may not run or may execute improperly.

See also
startPostponedEnterTransition

toString

fun toString(): String

unregisterForContextMenu

fun unregisterForContextMenu(view: View): Unit

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

Parameters
view: View

The view that should stop showing a context menu.

See also
registerForContextMenu