Android Guides | Samples

Android.App.Fragment Class

A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity.

See Also: Fragment


[Android.Runtime.Register("android/app/Fragment", DoNotGenerateAcw=true)]
public class Fragment : Object, IComponentCallbacks2, View+IOnCreateContextMenuListener, IDisposable


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.FragmentManager and Fragment.FragmentManager.

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:

Developer Guides

For more information about using fragments, read the Fragments developer guide.

Older Platforms

While the Fragment API was introduced in Build+VERSION_CODES.Honeycomb, a version of the API at is also available for use on older platforms through NoType:android/support/v4/app/FragmentActivity;Href=../../../reference/android/support/v4/app/FragmentActivity.html. See the blog post for more details.


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

  1. Fragment.OnAttach(Activity) called once the fragment is associated with its activity.
  2. Fragment.OnCreate(Bundle) called to do initial creation of the fragment.
  3. Fragment.OnCreateView(LayoutInflater,ViewGroup,ViewGroup) creates and returns the view hierarchy associated with the fragment.
  4. Fragment.OnActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.OnCreate(Bundle).
  5. Fragment.OnViewStateRestored(Bundle) tells the fragment that all of the saved state of its view hierarchy has been restored.
  6. Fragment.OnStart makes the fragment visible to the user (based on its containing activity being started).
  7. Fragment.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:

  1. Fragment.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.
  2. Fragment.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.
  3. Fragment.OnDestroyView allows the fragment to clean up resources associated with its View.
  4. Fragment.OnDestroy called to do final cleanup of the fragment's state.
  5. Fragment.OnDetach called immediately prior to the fragment no longer being associated with its activity.


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:

xml Example

<FrameLayout xmlns:android=""
    android:layout_width="match_parent" android:layout_height="match_parent">
    <fragment class="$TitlesFragment"
            android:layout_width="match_parent" android:layout_height="match_parent" />

The layout is installed in the activity in the normal way:

java Example

protected void onCreate(Bundle savedInstanceState) {


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.

java Example

public static class TitlesFragment extends ListFragment {
    boolean mDualPane;
    int mCurCheckPosition = 0;

    public void onActivityCreated(Bundle savedInstanceState) {

        // Populate list with our static array of titles.
        setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));

        // Check to see if we have a frame in which to embed the details
        // fragment directly in the containing UI.
        View detailsFrame = getActivity().findViewById(;
        mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

        if (savedInstanceState != null) {
            // Restore last state for checked position.
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);

        if (mDualPane) {
            // In dual-pane mode, the list view highlights the selected item.
            // Make sure our UI is in the correct state.

    public void onSaveInstanceState(Bundle outState) {
        outState.putInt("curChoice", mCurCheckPosition);

    public void onListItemClick(ListView l, View v, int position, long id) {

     * Helper function to show the details of a selected item, either by
     * displaying a fragment in-place in the current UI, or starting a
     * whole new activity in which it is displayed.
    void showDetails(int index) {
        mCurCheckPosition = index;

        if (mDualPane) {
            // We can display everything in-place with fragments, so update
            // the list to highlight the selected item and show the data.
            getListView().setItemChecked(index, true);

            // Check what fragment is currently shown, replace if needed.
            DetailsFragment details = (DetailsFragment)
            if (details == null || details.getShownIndex() != index) {
                // Make new fragment to show this selection.
                details = DetailsFragment.newInstance(index);

                // Execute a transaction, replacing any existing fragment
                // with this one inside the frame.
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                if (index == 0) {
                    ft.replace(, details);
                } else {
                    ft.replace(, details);

        } else {
            // Otherwise we need to launch a new activity to display
            // the dialog fragment with selected text.
            Intent intent = new Intent();
            intent.setClass(getActivity(), DetailsActivity.class);
            intent.putExtra("index", index);

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:

java Example

public static class DetailsFragment extends Fragment {
     * Create a new instance of DetailsFragment, initialized to
     * show the text at 'index'.
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);

        return f;

    public int getShownIndex() {
        return getArguments().getInt("index", 0);

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (container == null) {
            // We have different layouts, and in one of them this
            // fragment's containing frame doesn't exist.  The fragment
            // may still be created from its saved state, but there is
            // no reason to try to create its view hierarchy because it
            // won't be displayed.  Note this is not needed -- we could
            // just run the code below, where we would create and return
            // the view hierarchy; it would just never be used.
            return null;

        ScrollView scroller = new ScrollView(getActivity());
        TextView text = new TextView(getActivity());
        int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                4, getActivity().getResources().getDisplayMetrics());
        text.setPadding(padding, padding, padding, padding);
        return scroller;

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:

java Example

public static class DetailsActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {

        if (getResources().getConfiguration().orientation
                == Configuration.ORIENTATION_LANDSCAPE) {
            // If the screen is now in landscape mode, we can show the
            // dialog in-line with the list so we don't need this activity.

        if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            DetailsFragment details = new DetailsFragment();
            getFragmentManager().beginTransaction().add(, details).commit();

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:

xml Example

<LinearLayout xmlns:android=""
    android:layout_width="match_parent" android:layout_height="match_parent">

    <fragment class="$TitlesFragment"
            android:id="@+id/titles" android:layout_weight="1"
            android:layout_width="0px" android:layout_height="match_parent" />

    <FrameLayout android:id="@+id/details" android:layout_weight="1"
            android:layout_width="0px" android:layout_height="match_parent"
            android:background="?android:attr/detailsElementBackground" />


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 Fragment.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 Fragment.OnInflate(Activity,IAttributeSet,IAttributeSet) 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:

java Example

public static class CountingFragment extends Fragment {
    int mNum;

     * Create a new instance of CountingFragment, providing "num"
     * as an argument.
    static CountingFragment newInstance(int num) {
        CountingFragment f = new CountingFragment();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);

        return f;

     * When creating, retrieve this instance's number from its arguments.
    public void onCreate(Bundle savedInstanceState) {
        mNum = getArguments() != null ? getArguments().getInt("num") : 1;

     * The Fragment's UI is just a simple text view showing its
     * instance number.
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.hello_world, container, false);
        View tv = v.findViewById(;
        ((TextView)tv).setText("Fragment #" + mNum);
        return v;

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:

java Example

void addFragmentToStack() {

    // Instantiate a new fragment.
    Fragment newFragment = CountingFragment.newInstance(mStackLevel);

    // Add the fragment to the activity, pushing this transaction
    // on to the back stack.
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(, newFragment);

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.

[Android Documentation]


Namespace: Android.App
Assembly: Mono.Android (in Mono.Android.dll)
Assembly Versions:
Since: Added in API level 11

The members of Android.App.Fragment are listed below.

See Also: Object

Public Constructors

Default constructor.

Protected Constructors

A constructor used when creating managed representations of JNI objects; called by the runtime.

Public Properties

ActivityActivity. Return the Activity this fragment is currently associated with.
AllowEnterTransitionOverlapBoolean. Returns whether the the exit transition and enter transition overlap or not.
AllowReturnTransitionOverlapBoolean. Returns whether the the return transition and reenter transition overlap or not.
ArgumentsBundle. Return the arguments supplied to Fragment.Arguments, if any.
ChildFragmentManagerFragmentManager. Return a private FragmentManager for placing and managing Fragments inside of this Fragment.
EnterTransitionTransition. Returns the Transition that will be used to move Views into the initial scene.
ExitTransitionTransition. 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.
FragmentManagerFragmentManager. Return the FragmentManager for interacting with fragments associated with this fragment's activity.
IdInt32. Return the identifier this fragment is known by.
IsAddedBoolean. Return true if the fragment is currently added to its activity.
IsDetachedBoolean. Return true if the fragment has been explicitly detached from the UI.
IsHiddenBoolean. Return true if the fragment has been hidden.
IsInLayoutBoolean. Return true if the layout is included as part of an activity view hierarchy via the <fragment> tag.
IsRemovingBoolean. Return true if this fragment is currently being removed from its activity.
IsResumedBoolean. Return true if the fragment is in the resumed state.
IsVisibleBoolean. Return true if the fragment is currently visible to the user.
LoaderManagerLoaderManager. Return the LoaderManager for this fragment, creating it if needed.
ParentFragmentFragment. Returns the parent Fragment containing this Fragment.
ReenterTransitionTransition. Returns the Transition that will be used to move Views in to the scene when returning due to popping a back stack.
ResourcesResources. Return getActivity().getResources().
ReturnTransitionTransition. 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.
SharedElementEnterTransitionTransition. Returns the Transition that will be used for shared elements transferred into the content Scene.
SharedElementReturnTransitionTransition. Return the Transition that will be used for shared elements transferred back during a pop of the back stack.
TagString. Get the tag name of the fragment, if specified.
TargetFragmentFragment. Return the target fragment set by Fragment.SetTargetFragment(Fragment,Int32).
TargetRequestCodeInt32. Return the target request code set by Fragment.SetTargetFragment(Fragment,Int32).
ViewView. Get the root view for the fragment's layout (the one returned by Fragment.OnCreateView(LayoutInflater,ViewGroup,ViewGroup)), if provided.

Protected Properties

ThresholdClassIntPtr. This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
ThresholdTypeType. This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Public Methods

Dump(String, FileDescriptor, PrintWriter, String[])
Print the Fragments's state into the given stream.
Equals(Object) : Boolean
Subclasses can not override equals().
GetHashCode() : Int32
Subclasses can not override hashCode().
GetString(Int32) : String
Return a localized string from the application's package's default string table.
GetString(Int32, params Object[]) : String
GetText(Int32) : String
GetTextFormatted(Int32) : ICharSequence
Return a localized, styled CharSequence from the application's package's default string table.
Instantiate(Context, String) : Fragment
Like Fragment.Instantiate(Context,String,String) but with a null argument Bundle.
Instantiate(Context, String, Bundle) : Fragment
Create a new instance of a Fragment with the given class name.
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 Fragment.StartActivityForResult(Intent,Int32).
Called by the system when the device configuration changes while your component is running.
OnContextItemSelected(IMenuItem) : Boolean
This hook is called whenever an item in a context menu is selected.
Called to do initial creation of a fragment.
OnCreateAnimator(FragmentTransit, Boolean, Int32) : Animator
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) : View
Called to have the fragment instantiate its user interface view.
Called when the fragment is no longer in use.
Called when this fragment's option menu items are no longer being included in the overall options menu.
Called when the view previously created by Fragment.OnCreateView(LayoutInflater,ViewGroup,ViewGroup) has been detached from the fragment.
Called when the fragment is no longer attached to its activity.
Called when the hidden state (as returned by Fragment.IsHidden of the fragment has changed.
OnInflate(IAttributeSet, Bundle)
OnInflate(Activity, IAttributeSet, Bundle)
This is called when the overall system is running low on memory, and actively running processes should trim their memory usage.
OnOptionsItemSelected(IMenuItem) : Boolean
This hook is called whenever an item in your options menu is selected.
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).
Called when the Fragment is no longer resumed.
Prepare the Screen's standard options menu to be displayed.
Called when the fragment is visible to the user and actively running.
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.
Called when the Fragment is visible to the user.
Called when the Fragment is no longer started.
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 Fragment.OnCreateView(LayoutInflater,ViewGroup,ViewGroup) has returned, but before any saved state has been restored in to the view.
Called when all saved state has been restored into the view hierarchy of the fragment.
Registers a context menu to be shown for the given view (multiple views can show the context menu).
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.
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.
Report that this fragment would like to participate in populating the options menu by receiving a call to Fragment.OnCreateOptionsMenu(IMenu,MenuInflater) and related methods.
Set the initial saved state that this Fragment should restore itself from when first being constructed, as returned by FragmentManager.SaveFragmentInstanceState(Fragment).
Set a hint for whether this fragment's menu should be visible.
SetTargetFragment(Fragment, Int32)
Optional target for this fragment.
Call Context.StartActivity from the fragment's containing Activity.
StartActivity(Intent, Bundle)
Call Activity.startActivity(android.content.Intent, android.os.Bundle) from the fragment's containing Activity.
StartActivityForResult(Intent, Int32)
Call Activity.StartActivityForResult(Intent,Int32) from the fragment's containing Activity.
StartActivityForResult(Intent, Int32, Bundle)
Call Activity.StartActivityForResult(Intent,Int32,Int32) from the fragment's containing Activity.
Prevents a context menu to be shown for the given view.