Fragment

public class Fragment
extends Object implements ComponentCallbacks, View.OnCreateContextMenuListener, LifecycleOwner, ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner, ActivityResultCaller

java.lang.Object
   ↳ androidx.fragment.app.Fragment


Static library support version of the framework's 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 Fragment documentation for a class overview.

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

Summary

Nested classes

class Fragment.InstantiationException

Thrown by FragmentFactory.instantiate(ClassLoader, String) when there is an instantiation failure. 

class Fragment.SavedState

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

Public constructors

Fragment()

Constructor used by the default FragmentFactory.

Fragment(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(LayoutInflater, ViewGroup, Bundle).

Public methods

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

Print the Fragments's state into the given stream.

final boolean equals(Object o)

Subclasses can not override equals().

final FragmentActivity getActivity()

Return the FragmentActivity this fragment is currently associated with.

boolean getAllowEnterTransitionOverlap()

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

boolean getAllowReturnTransitionOverlap()

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

final Bundle getArguments()

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

final FragmentManager getChildFragmentManager()

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

Context getContext()

Return the Context this fragment is currently associated with.

ViewModelProvider.Factory getDefaultViewModelProviderFactory()

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

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

Object getEnterTransition()

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

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.

final FragmentManager getFragmentManager()

This method is deprecated. This has been removed in favor of getParentFragmentManager() which throws an IllegalStateException if the FragmentManager is null. Check if isAdded() returns false to determine if the FragmentManager is null.

final Object getHost()

Return the host object of this fragment.

final int getId()

Return the identifier this fragment is known by.

final LayoutInflater getLayoutInflater()

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

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.

LoaderManager getLoaderManager()

This method is deprecated. Use LoaderManager.getInstance(this).

final Fragment getParentFragment()

Returns the parent Fragment containing this Fragment.

final FragmentManager getParentFragmentManager()

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

Object getReenterTransition()

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

final Resources getResources()

Return requireActivity().getResources().

final boolean getRetainInstance()

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. The ViewModel's constructor and its onCleared() callback provide the signal for initial creation and final destruction of the retained state.

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.

final SavedStateRegistry getSavedStateRegistry()

Returns owned SavedStateRegistry

Object getSharedElementEnterTransition()

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

Object getSharedElementReturnTransition()

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

final String getString(int resId, Object... formatArgs)

Return a localized formatted string from the application's package's default string table, substituting the format arguments as defined in Formatter and String.format(String, Object...).

final String getString(int resId)

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

final String getTag()

Get the tag name of the fragment, if specified.

final Fragment getTargetFragment()

This method is deprecated. Instead of using a target fragment to pass results, use FragmentManager.setFragmentResult(String, Bundle) to deliver results to FragmentResultListener instances registered by other fragments via FragmentManager.setFragmentResultListener(String, LifecycleOwner, FragmentResultListener).

final int getTargetRequestCode()

This method is deprecated. When using the target fragment replacement of FragmentManager.setFragmentResultListener(String, LifecycleOwner, FragmentResultListener) and FragmentManager.setFragmentResult(String, Bundle), consider using setArguments(Bundle) to pass a requestKey if you need to support dynamic request keys.

final CharSequence getText(int resId)

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

boolean getUserVisibleHint()

This method is deprecated. Use FragmentTransaction.setMaxLifecycle(Fragment, Lifecycle.State) instead.

View getView()

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

LifecycleOwner getViewLifecycleOwner()

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

LiveData<LifecycleOwner> getViewLifecycleOwnerLiveData()

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

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.

final int hashCode()

Subclasses can not override hashCode().

static Fragment instantiate(Context context, String fname)

This method is deprecated. Use FragmentManager.getFragmentFactory() and FragmentFactory.instantiate(ClassLoader, String)

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

This method is deprecated. Use FragmentManager.getFragmentFactory() and FragmentFactory.instantiate(ClassLoader, String), manually calling setArguments(Bundle) on the returned Fragment.

final boolean isAdded()

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

final boolean isDetached()

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 isInLayout()

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

final boolean isRemoving()

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

final boolean isResumed()

Return true if the fragment is in the resumed state.

final boolean isStateSaved()

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

final boolean isVisible()

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

void onActivityCreated(Bundle savedInstanceState)

This method is deprecated. use onViewCreated(View, Bundle) for code touching the Fragment's view and onCreate(Bundle) for other initialization. To get a callback specifically when a Fragment activity's Activity.onCreate(Bundle) is called, register a LifecycleObserver on the Activity's Lifecycle in onAttach(Context), removing it when it receives the Lifecycle.State.CREATED callback.

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

This method is deprecated. use registerForActivityResult(ActivityResultContract, ActivityResultCallback) with the appropriate ActivityResultContract and handling the result in the callback.

void onAttach(Activity activity)

This method is deprecated. See onAttach(Context).

void onAttach(Context context)

Called when a fragment is first attached to its context.

void onAttachFragment(Fragment childFragment)

This method is deprecated. The responsibility for listening for fragments being attached has been moved to FragmentManager. You can add a listener to getChildFragmentManager() the child FragmentManager} by calling FragmentManager.addFragmentOnAttachListener(FragmentOnAttachListener) in onAttach(Context) to get callbacks when a child fragment is attached.

void onConfigurationChanged(Configuration newConfig)
boolean onContextItemSelected(MenuItem item)

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

void onCreate(Bundle savedInstanceState)

Called to do initial creation of a fragment.

Animation onCreateAnimation(int transit, boolean enter, int nextAnim)

Called when a fragment loads an animation.

Animator onCreateAnimator(int transit, boolean enter, int nextAnim)

Called when a fragment loads an animator.

void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)

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

void onCreateOptionsMenu(Menu menu, MenuInflater inflater)

Initialize the contents of the Fragment host's standard options menu.

View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

Called to have the fragment instantiate its user interface view.

void onDestroy()

Called when the fragment is no longer in use.

void onDestroyOptionsMenu()

Called when this fragment's option menu items are no longer being included in the overall options menu.

void onDestroyView()

Called when the view previously created by onCreateView(LayoutInflater, ViewGroup, Bundle) has been detached from the fragment.

void onDetach()

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

LayoutInflater onGetLayoutInflater(Bundle savedInstanceState)

Returns the LayoutInflater used to inflate Views of this Fragment.

void onHiddenChanged(boolean hidden)

Called when the hidden state (as returned by isHidden() of the fragment has changed.

void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState)

This method is deprecated. See onInflate(Context, AttributeSet, Bundle).

void onInflate(Context context, AttributeSet attrs, Bundle savedInstanceState)

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

void onLowMemory()
void onMultiWindowModeChanged(boolean isInMultiWindowMode)

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

boolean onOptionsItemSelected(MenuItem item)

This hook is called whenever an item in your options menu is selected.

void onOptionsMenuClosed(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).

void onPause()

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 onPrepareOptionsMenu(Menu menu)

Prepare the Fragment host's standard options menu to be displayed.

void onPrimaryNavigationFragmentChanged(boolean isPrimaryNavigationFragment)

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

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

This method is deprecated. use registerForActivityResult(ActivityResultContract, ActivityResultCallback) passing in a ActivityResultContracts.RequestMultiplePermissions object for the ActivityResultContract and handling the result in the callback.

void onResume()

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

void onSaveInstanceState(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.

void onStart()

Called when the Fragment is visible to the user.

void onStop()

Called when the Fragment is no longer started.

void onViewCreated(View view, Bundle savedInstanceState)

Called immediately after onCreateView(LayoutInflater, ViewGroup, Bundle) has returned, but before any saved state has been restored in to the view.

void onViewStateRestored(Bundle savedInstanceState)

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

void postponeEnterTransition()

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

final void postponeEnterTransition(long duration, TimeUnit timeUnit)

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

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

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

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

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

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

void registerForContextMenu(View view)

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

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

This method is deprecated. use registerForActivityResult(ActivityResultContract, ActivityResultCallback) passing in a ActivityResultContracts.RequestMultiplePermissions object for the ActivityResultContract and handling the result in the callback.

final FragmentActivity requireActivity()

Return the FragmentActivity this fragment is currently associated with.

final Bundle requireArguments()

Return the arguments supplied when the fragment was instantiated.

final Context requireContext()

Return the Context this fragment is currently associated with.

final FragmentManager requireFragmentManager()

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

final Object requireHost()

Return the host object of this fragment.

final Fragment requireParentFragment()

Returns the parent Fragment containing this Fragment.

final View requireView()

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

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(Bundle args)

Supply the construction arguments for this fragment.

void setEnterSharedElementCallback(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.

void setEnterTransition(Object transition)

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

void setExitSharedElementCallback(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.

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

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

void setInitialSavedState(Fragment.SavedState state)

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

void setMenuVisibility(boolean menuVisible)

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

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

This method is deprecated. Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment. The ViewModel's constructor and its onCleared() callback provide the signal for initial creation and final destruction of the retained state.

void setReturnTransition(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(Object transition)

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

void setSharedElementReturnTransition(Object transition)

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

void setTargetFragment(Fragment fragment, int requestCode)

This method is deprecated. Instead of using a target fragment to pass results, the fragment requesting a result should use FragmentManager.setFragmentResultListener(String, LifecycleOwner, FragmentResultListener) to register a FragmentResultListener with a requestKey using its parent fragment manager. The fragment delivering a result should then call FragmentManager.setFragmentResult(String, Bundle) using the same requestKey. Consider using setArguments(Bundle) to pass the requestKey if you need to support dynamic request keys.

void setUserVisibleHint(boolean isVisibleToUser)

This method is deprecated. If you are manually calling this method, use FragmentTransaction.setMaxLifecycle(Fragment, Lifecycle.State) instead. If overriding this method, behavior implemented when passing in true should be moved to onResume(), and behavior implemented when passing in false should be moved to onPause().

boolean shouldShowRequestPermissionRationale(String permission)

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

void startActivity(Intent intent)

Call Activity.startActivity(Intent) from the fragment's containing Activity.

void startActivity(Intent intent, Bundle options)

Call Activity.startActivity(Intent, Bundle) from the fragment's containing Activity.

void startActivityForResult(Intent intent, int requestCode)

This method is deprecated. use registerForActivityResult(ActivityResultContract, ActivityResultCallback) passing in a ActivityResultContracts.StartActivityForResult object for the ActivityResultContract.

void startActivityForResult(Intent intent, int requestCode, Bundle options)

This method is deprecated. use registerForActivityResult(ActivityResultContract, ActivityResultCallback) passing in a ActivityResultContracts.StartActivityForResult object for the ActivityResultContract.

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

This method is deprecated. use registerForActivityResult(ActivityResultContract, ActivityResultCallback) passing in a ActivityResultContracts.StartIntentSenderForResult object for the ActivityResultContract.

void startPostponedEnterTransition()

Begin postponed transitions after postponeEnterTransition() was called.

String toString()
void unregisterForContextMenu(View view)

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

Inherited methods

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(Bundle) 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(Context) 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(Activity, AttributeSet, Bundle) to retrieve attributes from a layout resource, although note this happens when the fragment is attached.

Fragment

public Fragment (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(LayoutInflater, ViewGroup, Bundle).

 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.

Parameters
contentLayoutId int

Public methods

dump

public void dump (String prefix, 
                FileDescriptor fd, 
                PrintWriter writer, 
                String[] args)

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 String: additional arguments to the dump request.

equals

public final boolean equals (Object o)

Subclasses can not override equals().

Parameters
o Object

Returns
boolean

getActivity

public final FragmentActivity getActivity ()

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

Returns
FragmentActivity

See also:

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 Bundle getArguments ()

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

Returns
Bundle

getChildFragmentManager

public final FragmentManager getChildFragmentManager ()

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

Returns
FragmentManager

getContext

public Context getContext ()

Return the Context this fragment is currently associated with.

Returns
Context

See also:

getDefaultViewModelProviderFactory

public ViewModelProvider.Factory getDefaultViewModelProviderFactory ()

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

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

Returns
ViewModelProvider.Factory a ViewModelProvider.Factory

getEnterTransition

public 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 ViewGroup.isTransitionGroup() return true. Typical Transitions will extend Visibility as entering is governed by changing visibility from View.INVISIBLE to View.VISIBLE.

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

getExitTransition

public 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 ViewGroup.isTransitionGroup() return true. Typical Transitions will extend Visibility as exiting is governed by changing visibility from View.VISIBLE to View.INVISIBLE. If transition is null, the views will remain unaffected.

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

getFragmentManager

public final FragmentManager getFragmentManager ()

This method is deprecated.
This has been removed in favor of getParentFragmentManager() which throws an IllegalStateException if the FragmentManager is null. Check if isAdded() returns false to determine if the FragmentManager is null.

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

Returns
FragmentManager

getHost

public final Object getHost ()

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

Returns
Object

See also:

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.

Returns
int

getLayoutInflater

public final LayoutInflater getLayoutInflater ()

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

The cached LayoutInflater will be replaced immediately prior to onCreateView(LayoutInflater, ViewGroup, Bundle) and cleared immediately after onDetach().

Returns
LayoutInflater The LayoutInflater used to inflate Views of this Fragment.

getLifecycle

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

Returns
Lifecycle The lifecycle of the provider.

getLoaderManager

public LoaderManager getLoaderManager ()

This method is deprecated.
Use LoaderManager.getInstance(this).

Return the LoaderManager for this fragment.

Returns
LoaderManager

getParentFragment

public final Fragment getParentFragment ()

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

Returns
Fragment

getParentFragmentManager

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

Returns
FragmentManager

Throws
IllegalStateException if not associated with a transaction or host.

getReenterTransition

public 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 ViewGroup.isTransitionGroup() return true. Typical Transitions will extend Visibility as exiting is governed by changing visibility from View.VISIBLE to View.INVISIBLE. If nothing is set, the default will be to use the same transition as getExitTransition().

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

getResources

public final Resources getResources ()

Return requireActivity().getResources().

Returns
Resources

getRetainInstance

public final boolean getRetainInstance ()

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. The ViewModel's constructor and its onCleared() callback provide the signal for initial creation and final destruction of the retained state.

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

Returns
boolean whether or not this fragment instance will be retained.

getReturnTransition

public 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 ViewGroup.isTransitionGroup() return true. Typical Transitions will extend Visibility as entering is governed by changing visibility from View.VISIBLE to View.INVISIBLE. If nothing is set, the default will be to use the same transition as getEnterTransition().

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

getSavedStateRegistry

public final SavedStateRegistry getSavedStateRegistry ()

Returns owned SavedStateRegistry

Returns
SavedStateRegistry a SavedStateRegistry

getSharedElementEnterTransition

public 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 ChangeBounds. A null value will cause transferred shared elements to blink to the final position.

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

getSharedElementReturnTransition

public 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 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(Object).

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

getString

public final String getString (int resId, 
                Object... formatArgs)

Return a localized formatted string from the application's package's default string table, substituting the format arguments as defined in Formatter and String.format(String, Object...).

Parameters
resId int: Resource id for the format string

formatArgs Object: The format arguments that will be used for substitution.

Returns
String

getString

public final String getString (int resId)

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

Parameters
resId int: Resource id for the string

Returns
String

getTag

public final String getTag ()

Get the tag name of the fragment, if specified.

Returns
String

getTargetFragment

public final Fragment getTargetFragment ()

This method is deprecated.
Instead of using a target fragment to pass results, use FragmentManager.setFragmentResult(String, Bundle) to deliver results to FragmentResultListener instances registered by other fragments via FragmentManager.setFragmentResultListener(String, LifecycleOwner, FragmentResultListener).

Return the target fragment set by setTargetFragment(Fragment, int).

Returns
Fragment

getTargetRequestCode

public final int getTargetRequestCode ()

This method is deprecated.
When using the target fragment replacement of FragmentManager.setFragmentResultListener(String, LifecycleOwner, FragmentResultListener) and FragmentManager.setFragmentResult(String, Bundle), consider using setArguments(Bundle) to pass a requestKey if you need to support dynamic request keys.

Return the target request code set by setTargetFragment(Fragment, int).

Returns
int

getText

public final CharSequence getText (int resId)

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

Parameters
resId int: Resource id for the CharSequence text

Returns
CharSequence

getUserVisibleHint

public boolean getUserVisibleHint ()

This method is deprecated.
Use FragmentTransaction.setMaxLifecycle(Fragment, Lifecycle.State) instead.

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

getView

public View getView ()

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

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

getViewLifecycleOwner

public LifecycleOwner getViewLifecycleOwner ()

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

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

  1. created after onViewStateRestored(Bundle)
  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(LayoutInflater, ViewGroup, Bundle) 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 FragmentTransaction.runOnCommit(Runnable) 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
IllegalStateException if the Fragment's View is null.

getViewLifecycleOwnerLiveData

public 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(LayoutInflater, ViewGroup, Bundle) 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

public 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
ViewModelStore a ViewModelStore

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

hashCode

public final int hashCode ()

Subclasses can not override hashCode().

Returns
int

instantiate

public static Fragment instantiate (Context context, 
                String fname)

This method is deprecated.
Use FragmentManager.getFragmentFactory() and FragmentFactory.instantiate(ClassLoader, String)

Like instantiate(Context, String, Bundle) but with a null argument Bundle.

Parameters
context Context

fname String

Returns
Fragment

instantiate

public static Fragment instantiate (Context context, 
                String fname, 
                Bundle args)

This method is deprecated.
Use FragmentManager.getFragmentFactory() and FragmentFactory.instantiate(ClassLoader, String), manually calling setArguments(Bundle) on the returned 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(Bundle).

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

Returns
boolean

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.

Returns
boolean

isHidden

public final boolean isHidden ()

Return true if the fragment has been hidden. By default fragments are shown. You can find out about changes to this state with onHiddenChanged(boolean). 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.

Returns
boolean

isInLayout

public final boolean isInLayout ()

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

Returns
boolean

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.

Returns
boolean

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.

Returns
boolean

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(Bundle) 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.

Returns
boolean

onActivityCreated

public void onActivityCreated (Bundle savedInstanceState)

This method is deprecated.
use onViewCreated(View, Bundle) for code touching the Fragment's view and onCreate(Bundle) for other initialization. To get a callback specifically when a Fragment activity's Activity.onCreate(Bundle) is called, register a LifecycleObserver on the Activity's Lifecycle in onAttach(Context), removing it when it receives the Lifecycle.State.CREATED callback.

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(boolean) 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(LayoutInflater, ViewGroup, Bundle) and before onViewStateRestored(Bundle).

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

onActivityResult

public void onActivityResult (int requestCode, 
                int resultCode, 
                Intent data)

This method is deprecated.
use registerForActivityResult(ActivityResultContract, ActivityResultCallback) with the appropriate ActivityResultContract and handling the result in the callback.

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

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

public void onAttach (Activity activity)

This method is deprecated.
See onAttach(Context).

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

Parameters
activity Activity

onAttach

public void onAttach (Context context)

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

Parameters
context Context

onAttachFragment

public void onAttachFragment (Fragment childFragment)

This method is deprecated.
The responsibility for listening for fragments being attached has been moved to FragmentManager. You can add a listener to getChildFragmentManager() the child FragmentManager} by calling FragmentManager.addFragmentOnAttachListener(FragmentOnAttachListener) in onAttach(Context) to get callbacks when a child fragment is attached.

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

public void onConfigurationChanged (Configuration newConfig)

Parameters
newConfig Configuration

onContextItemSelected

public boolean onContextItemSelected (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 MenuItem.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

public void onCreate (Bundle savedInstanceState)

Called to do initial creation of a fragment. This is called after onAttach(Activity) and before onCreateView(LayoutInflater, ViewGroup, Bundle).

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 LifecycleObserver on the activity's Lifecycle, removing it when it receives the Lifecycle.State.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

public Animation onCreateAnimation (int transit, 
                boolean enter, 
                int nextAnim)

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

Parameters
transit int: The value set in FragmentTransaction.setTransition(int) 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 FragmentTransaction.setCustomAnimations(int, int), FragmentTransaction.setCustomAnimations(int, int, int, int), or 0 if neither was called. The value will depend on the current operation.

Returns
Animation

onCreateAnimator

public Animator onCreateAnimator (int transit, 
                boolean enter, 
                int nextAnim)

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

Parameters
transit int: The value set in FragmentTransaction.setTransition(int) 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 FragmentTransaction.setCustomAnimations(int, int), FragmentTransaction.setCustomAnimations(int, int, int, int), or 0 if neither was called. The value will depend on the current operation.

Returns
Animator

onCreateContextMenu

public void onCreateContextMenu (ContextMenu menu, 
                View v, 
                ContextMenu.ContextMenuInfo menuInfo)

Called when a context menu for the view is about to be shown. Unlike onCreateOptionsMenu(Menu, MenuInflater), 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(android.view.MenuItem) 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.

Parameters
menu ContextMenu

v View

menuInfo ContextMenu.ContextMenuInfo

onCreateOptionsMenu

public void onCreateOptionsMenu (Menu menu, 
                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(boolean). See Activity.onCreateOptionsMenu for more information.

Parameters
menu Menu: The options menu in which you place your items.

inflater MenuInflater

onCreateView

public View onCreateView (LayoutInflater inflater, 
                ViewGroup container, 
                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(Bundle) and onViewCreated(View, Bundle).

A default View can be returned by calling Fragment(int) 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(View, Bundle).

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

public void onDestroy ()

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

onDestroyOptionsMenu

public void onDestroyOptionsMenu ()

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

onDestroyView

public void onDestroyView ()

Called when the view previously created by onCreateView(LayoutInflater, ViewGroup, Bundle) 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(LayoutInflater, ViewGroup, Bundle) 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

public void onDetach ()

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

onGetLayoutInflater

public LayoutInflater onGetLayoutInflater (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
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

public void onHiddenChanged (boolean hidden)

Called when the hidden state (as returned by isHidden() of the fragment 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

public void onInflate (Activity activity, 
                AttributeSet attrs, 
                Bundle savedInstanceState)

This method is deprecated.
See onInflate(Context, AttributeSet, Bundle).

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

Parameters
activity Activity

attrs AttributeSet

savedInstanceState Bundle

onInflate

public void onInflate (Context context, 
                AttributeSet attrs, 
                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(Context) 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

public void onLowMemory ()

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