Fragment Class
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
This class was deprecated in API level 28.
[Android.Runtime.Register("android/app/Fragment", DoNotGenerateAcw=true)]
public class Fragment : Java.Lang.Object, Android.Content.IComponentCallbacks2, Android.Views.View.IOnCreateContextMenuListener, IDisposable, Java.Interop.IJavaPeerable
[<Android.Runtime.Register("android/app/Fragment", DoNotGenerateAcw=true)>]
type Fragment = class
inherit Object
interface IComponentCallbacks2
interface IComponentCallbacks
interface IJavaObject
interface IDisposable
interface IJavaPeerable
interface View.IOnCreateContextMenuListener
- Inheritance
- Derived
- Attributes
- Implements
Remarks
This class was deprecated in API level 28. Use the Jetpack Fragment Library Fragment for consistent behavior across all devices and access to Lifecycle.
A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity. Interaction with fragments is done through FragmentManager, which can be obtained via Activity.getFragmentManager() and Fragment.getFragmentManager(). The Fragment class can be used many ways to achieve a wide variety of results. In its core, it represents a particular operation or interface that is running within a larger Activity. A Fragment is closely tied to the Activity it is in, and can not be used apart from one. Though Fragment defines its own lifecycle, that lifecycle is dependent on its activity: if the activity is stopped, no fragments inside of it can be started; when the activity is destroyed, all fragments will be destroyed. All subclasses of Fragment must include a public no-argument constructor. The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it. If the no-argument constructor is not available, a runtime exception will occur in some cases during state restore. Topics covered here: Older Platforms Lifecycle Layout Back Stack Developer Guides For more information about using fragments, read the Fragments developer guide.
Though a Fragment's lifecycle is tied to its owning activity, it has its own wrinkle on the standard activity lifecycle. It includes basic activity lifecycle methods such as onResume(), but also important are methods related to interactions with the activity and UI generation. The core series of lifecycle methods that are called to bring a fragment up to resumed state (interacting with the user) are: onAttach(Activity) called once the fragment is associated with its activity. onCreate(Bundle) called to do initial creation of the fragment. onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment. onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.onCreate(). onViewStateRestored(Bundle) tells the fragment that all of the saved state of its view hierarchy has been restored. onStart() makes the fragment visible to the user (based on its containing activity being started). onResume() makes the fragment begin interacting with the user (based on its containing activity being resumed). As a fragment is no longer being used, it goes through a reverse series of callbacks: onPause() fragment is no longer interacting with the user either because its activity is being paused or a fragment operation is modifying it in the activity. onStop() fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity. onDestroyView() allows the fragment to clean up resources associated with its View. onDestroy() called to do final cleanup of the fragment's state. onDetach() called immediately prior to the fragment no longer being associated with its activity. Layout Fragments can be used as part of your application's layout, allowing you to better modularize your code and more easily adjust your user interface to the screen it is running on. As an example, we can look at a simple program consisting of a list of items, and display of the details of each item.
An activity's layout XML can include <fragment> tags to embed fragment instances inside of the layout. For example, here is a simple layout that embeds one fragment:
The layout is installed in the activity in the normal way:
The titles fragment, showing a list of titles, is fairly simple, relying on ListFragment for most of its work. Note the implementation of clicking an item: depending on the current activity's layout, it can either create and display a new fragment to show the details in-place (more about this later), or start a new activity to show the details.
The details fragment showing the contents of a selected item just displays a string of text based on an index of a string array built in to the app:
In this case when the user clicks on a title, there is no details container in the current activity, so the titles fragment's click code will launch a new activity to display the details fragment:
However the screen may be large enough to show both the list of titles and details about the currently selected title. To use such a layout on a landscape screen, this alternative layout can be placed under layout-land:
Note how the prior code will adjust to this alternative UI flow: the titles fragment will now embed the details fragment inside of this activity, and the details activity will finish itself if it is running in a configuration where the details can be shown in-place. When a configuration change causes the activity hosting these fragments to restart, its new instance may use a different layout that doesn't include the same fragments as the previous layout. In this case all of the previous fragments will still be instantiated and running in the new instance. However, any that are no longer associated with a <fragment> tag in the view hierarchy will not have their content view created and will return false from isInLayout(). (The code here also shows how you can determine if a fragment placed in a container is no longer running in a layout with that container and avoid creating its view hierarchy in that case.) The attributes of the <fragment> tag are used to control the LayoutParams provided when attaching the fragment's view to the parent container. They can also be parsed by the fragment in onInflate(Activity, AttributeSet, Bundle) as parameters. The fragment being instantiated must have some kind of unique identifier so that it can be re-associated with a previous instance if the parent activity needs to be destroyed and recreated. This can be provided these ways: If nothing is explicitly supplied, the view ID of the container will be used. android:tag can be used in <fragment> to provide a specific tag name for the fragment. android:id can be used in <fragment> to provide a specific identifier for the fragment. Back Stack The transaction in which fragments are modified can be placed on an internal back-stack of the owning activity. When the user presses back in the activity, any transactions on the back stack are popped off before the activity itself is finished. For example, consider this simple fragment that is instantiated with an integer argument and displays that in a TextView in its UI:
A function that creates a new instance of the fragment, replacing whatever current fragment instance is being shown and pushing that change on to the back stack could be written as: After each call to this function, a new entry is on the stack, and pressing back will pop it to return the user to whatever previous state the activity UI was in. Fragments appearing or disappearing do not generate system events for accessibility, so set a title on your fragments with View.setAccessibilityPaneTitle(CharSequence) to notify accessibility users of these UI transitions.
Android reference for android.app.Fragment.
Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
Constructors
| Name | Description |
|---|---|
| Fragment() |
Default constructor. |
| Fragment(IntPtr, JniHandleOwnership) |
Initializes a managed representation of an existing Java Native Interface object. |
Properties
| Name | Description |
|---|---|
| Activity |
Return the Activity this fragment is currently associated with. |
| AllowEnterTransitionOverlap |
Returns whether the exit transition and enter transition overlap or not. |
| AllowReturnTransitionOverlap |
Returns whether the return transition and reenter transition overlap or not. |
| Arguments |
Return the arguments supplied to setArguments(Bundle), if any. |
| ChildFragmentManager |
Return a private FragmentManager for placing and managing Fragments inside of this Fragment. |
| Class |
Returns the runtime class of this |
| Context |
Return the Context this fragment is currently associated with. |
| EnterTransition |
Returns the Transition that will be used to move Views into the initial scene. |
| ExitTransition |
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 |
Return the FragmentManager for interacting with fragments associated with this fragment's activity. |
| Handle |
The handle to the underlying Android instance. (Inherited from Object) |
| Host |
Return the host object of this fragment. |
| Id |
Return the identifier this fragment is known by. |
| IsAdded |
Return true if the fragment is currently added to its activity. |
| IsDetached |
Return true if the fragment has been explicitly detached from the UI. |
| IsHidden |
Return true if the fragment has been hidden. |
| IsInLayout |
Return true if the layout is included as part of an activity view hierarchy via the <fragment> tag. |
| IsRemoving |
Return true if this fragment is currently being removed from its activity. |
| IsResumed |
Return true if the fragment is in the resumed state. |
| IsStateSaved |
Returns true if this fragment is added and its state has already been saved by its host. |
| IsVisible |
Return true if the fragment is currently visible to the user. |
| JniIdentityHashCode |
Gets the identity hash code assigned to this Java peer by the interop runtime. (Inherited from Object) |
| JniPeerMembers |
Provides JNI binding infrastructure for Android.App.Fragment. |
| LayoutInflater |
Returns the cached LayoutInflater used to inflate Views of this Fragment. |
| LoaderManager |
This method is deprecated. |
| ParentFragment |
Returns the parent Fragment containing this Fragment. |
| PeerReference |
Gets the JNI object reference for this Java peer. (Inherited from Object) |
| ReenterTransition |
Returns the Transition that will be used to move Views in to the scene when returning due to popping a back stack. |
| Resources |
Return getActivity().getResources(). |
| RetainInstance |
Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). |
| ReturnTransition |
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. |
| SharedElementEnterTransition |
Returns the Transition that will be used for shared elements transferred into the content Scene. |
| SharedElementReturnTransition |
Return the Transition that will be used for shared elements transferred back during a pop of the back stack. |
| Tag |
Get the tag name of the fragment, if specified. |
| TargetFragment |
Return the target fragment set by setTargetFragment(Fragment, int). |
| TargetRequestCode |
Return the target request code set by setTargetFragment(Fragment, int). |
| ThresholdClass |
Provides JNI binding infrastructure for Android.App.Fragment. |
| ThresholdType |
Provides JNI binding infrastructure for Android.App.Fragment. |
| UserVisibleHint |
See also: |
| View |
Get the root view for the fragment's layout (the one returned by onCreateView(LayoutInflater, ViewGroup, Bundle)), if provided. |
Methods
| Name | Description |
|---|---|
| Clone() |
Creates and returns a copy of this object. (Inherited from Object) |
| Dispose() |
Releases the resources held by this Java peer. (Inherited from Object) |
| Dispose(Boolean) |
Releases the resources held by this Java peer. (Inherited from Object) |
| Dump(String, FileDescriptor, PrintWriter, String[]) |
Print the Fragments's state into the given stream. |
| Equals(Object) |
Obsolete.
Subclasses can not override equals(). |
| GetHashCode() |
Obsolete.
Subclasses can not override hashCode(). |
| GetString(Int32, Object[]) |
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). |
| GetString(Int32) |
Return a localized string from the application's package's default string table. |
| GetText(Int32) |
Return a localized, styled CharSequence from the application's package's default string table. |
| GetTextFormatted(Int32) |
Return a localized, styled CharSequence from the application's package's default string table. |
| Instantiate(Context, String, Bundle) |
Create a new instance of a Fragment with the given class name. |
| Instantiate(Context, String) |
Like instantiate(Context,String,Bundle) but with a null argument Bundle. |
| JavaFinalize() |
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. (Inherited from Object) |
| Notify() |
Wakes up a single thread that is waiting on this object's monitor. (Inherited from Object) |
| NotifyAll() |
Wakes up all threads that are waiting on this object's monitor. (Inherited from Object) |
| OnActivityCreated(Bundle) |
Called when the fragment's activity has been created and this fragment's view hierarchy instantiated. |
| OnActivityResult(Int32, Result, Intent) |
Receive the result from a previous call to startActivityForResult(Intent,int). |
| OnAttach(Activity) |
This method was deprecated in API level 23. |
| OnAttach(Context) |
Called when a fragment is first attached to its context. |
| OnAttachFragment(Fragment) |
Called when a fragment is attached as a child of this fragment. |
| OnConfigurationChanged(Configuration) |
Called by the system when the device configuration changes while your component is running. |
| OnContextItemSelected(IMenuItem) |
This hook is called whenever an item in a context menu is selected. |
| OnCreate(Bundle) |
Called to do initial creation of a fragment. |
| OnCreateAnimator(FragmentTransit, Boolean, Int32) |
Called when a fragment loads an animation. |
| OnCreateContextMenu(IContextMenu, View, IContextMenuContextMenuInfo) |
Called when a context menu for the view is about to be shown. |
| OnCreateOptionsMenu(IMenu, MenuInflater) |
Initialize the contents of the Activity's standard options menu. |
| OnCreateView(LayoutInflater, ViewGroup, Bundle) |
Called to have the fragment instantiate its user interface view. |
| OnDestroy() |
Called when the fragment is no longer in use. |
| OnDestroyOptionsMenu() |
Called when this fragment's option menu items are no longer being included in the overall options menu. |
| OnDestroyView() |
Called when the view previously created by onCreateView(LayoutInflater, ViewGroup, Bundle) has been detached from the fragment. |
| OnDetach() |
Called when the fragment is no longer attached to its activity. |
| OnGetLayoutInflater(Bundle) |
Returns the LayoutInflater used to inflate Views of this Fragment. |
| OnHiddenChanged(Boolean) |
Called when the hidden state (as returned by isHidden() of the fragment has changed. |
| OnInflate(Activity, IAttributeSet, Bundle) |
This method was deprecated in API level 23. |
| OnInflate(Context, IAttributeSet, Bundle) |
Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity. |
| OnInflate(IAttributeSet, Bundle) |
Obsolete.
This method was deprecated in API level 15. |
| OnLowMemory() |
This is called when the overall system is running low on memory, and actively running processes should trim their memory usage. |
| OnMultiWindowModeChanged(Boolean, Configuration) |
Called when the Fragment's activity changes from fullscreen mode to multi-window mode and visa-versa. |
| OnMultiWindowModeChanged(Boolean) |
This method was deprecated in API level 26. |
| OnOptionsItemSelected(IMenuItem) |
This hook is called whenever an item in your options menu is selected. |
| OnOptionsMenuClosed(IMenu) |
This hook is called whenever the options menu is being closed (either by the user canceling the menu with the back/menu button, or when an item is selected). |
| OnPause() |
Called when the Fragment is no longer resumed. |
| OnPictureInPictureModeChanged(Boolean, Configuration) |
Called by the system when the activity changes to and from picture-in-picture mode. |
| OnPictureInPictureModeChanged(Boolean) |
This method was deprecated in API level 26. |
| OnPrepareOptionsMenu(IMenu) |
Prepare the Screen's standard options menu to be displayed. |
| OnRequestPermissionsResult(Int32, String[], Permission[]) |
Callback for the result from requesting permissions. |
| OnResume() |
Called when the fragment is visible to the user and actively running. |
| OnSaveInstanceState(Bundle) |
Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance of its process is restarted. |
| OnStart() |
Called when the Fragment is visible to the user. |
| OnStop() |
Called when the Fragment is no longer started. |
| OnTrimMemory(TrimMemory) |
Called when the operating system has determined that it is a good time for a process to trim unneeded memory from its process. |
| OnViewCreated(View, Bundle) |
Called immediately after onCreateView(LayoutInflater,ViewGroup,Bundle) has returned, but before any saved state has been restored in to the view. |
| OnViewStateRestored(Bundle) |
Called when all saved state has been restored into the view hierarchy of the fragment. |
| PostponeEnterTransition() |
Postpone the entering Fragment transition until startPostponedEnterTransition() or FragmentManager.executePendingTransactions() has been called. |
| RegisterForContextMenu(View) |
Registers a context menu to be shown for the given view (multiple views can show the context menu). |
| RequestPermissions(String[], Int32) |
Requests permissions to be granted to this application. |
| SetEnterSharedElementCallback(SharedElementCallback) |
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. |
| SetExitSharedElementCallback(SharedElementCallback) |
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. |
| SetHandle(IntPtr, JniHandleOwnership) |
Sets the Handle property. (Inherited from Object) |
| SetHasOptionsMenu(Boolean) |
Report that this fragment would like to participate in populating the options menu by receiving a call to onCreateOptionsMenu(Menu, MenuInflater) and related methods. |
| SetInitialSavedState(Fragment+SavedState) |
Set the initial saved state that this Fragment should restore itself from when first being constructed, as returned by FragmentManager.saveFragmentInstanceState. |
| SetMenuVisibility(Boolean) |
Set a hint for whether this fragment's menu should be visible. |
| SetTargetFragment(Fragment, Int32) |
Optional target for this fragment. |
| ShouldShowRequestPermissionRationale(String) |
Gets whether you should show UI with rationale before requesting a permission. |
| StartActivity(Intent, Bundle) |
Call Activity.startActivity(Intent,Bundle) from the fragment's containing Activity. |
| StartActivity(Intent) |
Call Activity.startActivity(Intent) from the fragment's containing Activity. |
| StartActivityForResult(Intent, Int32, Bundle) |
Call Activity.startActivityForResult(Intent,int,Bundle) from the fragment's containing Activity. |
| StartActivityForResult(Intent, Int32) |
Call Activity.startActivityForResult(Intent,int) from the fragment's containing Activity. |
| StartIntentSenderForResult(IntentSender, Int32, Intent, ActivityFlags, ActivityFlags, Int32, Bundle) |
Call Activity.startIntentSenderForResult(IntentSender,int,Intent,int,int,int,Bundle) from the fragment's containing Activity. |
| StartPostponedEnterTransition() |
Begin postponed transitions after postponeEnterTransition() was called. |
| ToArray<T>() |
Creates a managed array from this Java array wrapper. (Inherited from Object) |
| ToString() |
Returns a string representation of the object. (Inherited from Object) |
| UnregisterForContextMenu(View) |
Prevents a context menu to be shown for the given view. |
| UnregisterFromRuntime() |
Unregisters this Java peer from the interop runtime. (Inherited from Object) |
| Wait() |
Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>. (Inherited from Object) |
| Wait(Int64, Int32) |
Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed. (Inherited from Object) |
| Wait(Int64) |
Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed. (Inherited from Object) |
Explicit Interface Implementations
| Name | Description |
|---|---|
| IJavaPeerable.Disposed() |
Notifies the interop runtime that this managed peer has been disposed. (Inherited from Object) |
| IJavaPeerable.DisposeUnlessReferenced() |
Releases this Java peer unless it is retained by another managed reference. (Inherited from Object) |
| IJavaPeerable.Finalized() |
Notifies the interop runtime that this managed peer has been finalized. (Inherited from Object) |
| IJavaPeerable.JniManagedPeerState |
Gets the state that describes the relationship between this managed peer and its JNI reference. (Inherited from Object) |
| IJavaPeerable.SetJniIdentityHashCode(Int32) |
Sets the interop identity hash code for this Java peer. (Inherited from Object) |
| IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) |
Sets the managed and JNI peer state for this Java peer. (Inherited from Object) |
| IJavaPeerable.SetPeerReference(JniObjectReference) |
Sets the JNI object reference used by this managed peer. (Inherited from Object) |
Extension Methods
| Name | Description |
|---|---|
| GetJniTypeName(IJavaPeerable) |
Gets the JNI name of the type of the instance |
| JavaAs<TResult>(IJavaPeerable) |
Try to coerce |
| JavaCast<TResult>(IJavaObject) |
Performs an Android runtime-checked type conversion. |
| JavaCast<TResult>(IJavaObject) | |
| TryJavaCast<TResult>(IJavaPeerable, TResult) |
Try to coerce |