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

Syntax

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

Remarks

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.

Lifecycle

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.

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:

xml Example

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"
            android:id="@+id/titles"
            android:layout_width="match_parent" android:layout_height="match_parent" />
</FrameLayout>

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

java Example

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.fragment_layout);
}

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;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(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(R.id.details);
        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.
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            // Make sure our UI is in the correct state.
            showDetails(mCurCheckPosition);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        showDetails(position);
    }

    /**
     * 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)
                    getFragmentManager().findFragmentById(R.id.details);
            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(R.id.details, details);
                } else {
                    ft.replace(R.id.a_item, details);
                }
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }

        } 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);
            startActivity(intent);
        }
    }
}

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);
        f.setArguments(args);

        return f;
    }

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

    @Override
    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);
        scroller.addView(text);
        text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
        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 {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(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.
            finish();
            return;
        }

        if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            DetailsFragment details = new DetailsFragment();
            details.setArguments(getIntent().getExtras());
            getFragmentManager().beginTransaction().add(android.R.id.content, 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="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <fragment class="com.example.android.apis.app.FragmentLayout$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" />

</LinearLayout>

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);
        f.setArguments(args);

        return f;
    }

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

    /**
     * The Fragment's UI is just a simple text view showing its
     * instance number.
     */
    @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("Fragment #" + mNum);
        tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
        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() {
    mStackLevel++;

    // 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(R.id.simple_fragment, newFragment);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    ft.addToBackStack(null);
    ft.commit();
}

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]

Requirements

Namespace: Android.App
Assembly: Mono.Android (in Mono.Android.dll)
Assembly Versions: 0.0.0.0
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

[read-only]
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.
[read-only]
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.
[read-only]
FragmentManagerFragmentManager. Return the FragmentManager for interacting with fragments associated with this fragment's activity.
[read-only]
IdInt32. Return the identifier this fragment is known by.
[read-only]
IsAddedBoolean. Return true if the fragment is currently added to its activity.
[read-only]
IsDetachedBoolean. Return true if the fragment has been explicitly detached from the UI.
[read-only]
IsHiddenBoolean. Return true if the fragment has been hidden.
[read-only]
IsInLayoutBoolean. Return true if the layout is included as part of an activity view hierarchy via the <fragment> tag.
[read-only]
IsRemovingBoolean. Return true if this fragment is currently being removed from its activity.
[read-only]
IsResumedBoolean. Return true if the fragment is in the resumed state.
[read-only]
IsVisibleBoolean. Return true if the fragment is currently visible to the user.
[read-only]
LoaderManagerLoaderManager. Return the LoaderManager for this fragment, creating it if needed.
[read-only]
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.
[read-only]
ResourcesResources. Return getActivity().getResources().
RetainInstanceBoolean.
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.
[read-only]
TagString. Get the tag name of the fragment, if specified.
[read-only]
TargetFragmentFragment. Return the target fragment set by Fragment.SetTargetFragment(Fragment,Int32).
[read-only]
TargetRequestCodeInt32. Return the target request code set by Fragment.SetTargetFragment(Fragment,Int32).
UserVisibleHintBoolean.
[read-only]
ViewView. Get the root view for the fragment's layout (the one returned by Fragment.OnCreateView(LayoutInflater,ViewGroup,ViewGroup)), if provided.

Protected Properties

[read-only]
override
ThresholdClassIntPtr. This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
[read-only]
override
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.
override
Equals(Object) : Boolean
Subclasses can not override equals().
override
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.
static
Instantiate(Context, String) : Fragment
Like Fragment.Instantiate(Context,String,String) but with a null argument Bundle.
static
Instantiate(Context, String, Bundle) : Fragment
Create a new instance of a Fragment with the given class name.
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 Fragment.StartActivityForResult(Intent,Int32).
OnAttach(Activity)
OnConfigurationChanged(Configuration)
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.
OnCreate(Bundle)
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.
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 Fragment.OnCreateView(LayoutInflater,ViewGroup,ViewGroup) has been detached from the fragment.
OnDetach()
Called when the fragment is no longer attached to its activity.
OnHiddenChanged(Boolean)
Called when the hidden state (as returned by Fragment.IsHidden of the fragment has changed.
OnInflate(IAttributeSet, Bundle)
OnInflate(Activity, IAttributeSet, Bundle)
OnLowMemory()
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.
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.
OnPrepareOptionsMenu(IMenu)
Prepare the Screen's standard options menu to be displayed.
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 Fragment.OnCreateView(LayoutInflater,ViewGroup,ViewGroup) 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.
RegisterForContextMenu(View)
Registers a context menu to be shown for the given view (multiple views can show the context menu).
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.
SetHasOptionsMenu(Boolean)
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.
SetInitialSavedState(Fragment+SavedState)
Set the initial saved state that this Fragment should restore itself from when first being constructed, as returned by FragmentManager.SaveFragmentInstanceState(Fragment).
SetMenuVisibility(Boolean)
Set a hint for whether this fragment's menu should be visible.
SetTargetFragment(Fragment, Int32)
Optional target for this fragment.
StartActivity(Intent)
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.
UnregisterForContextMenu(View)
Prevents a context menu to be shown for the given view.