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.

Older Platforms

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

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

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:

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:

Level for onTrimMemory(int): the process is around the middle
of the background LRU list; freeing memory can help the system keep
other processes running later in the list for better overall performance.

Level for onTrimMemory(int): the process is not an expendable
background process, but the device is running extremely low on memory
and is about to not be able to keep any background processes running.

Related Methods

Public Constructors

public
Fragment()

Default constructor. Every fragment must have an
empty constructor, so it can be instantiated when restoring its
activity's state. It is strongly recommended that subclasses do not
have other constructors with parameters, since these constructors
will not be called when the fragment is re-instantiated; instead,
arguments can be supplied by the caller with setArguments(Bundle)
and later retrieved by the Fragment with getArguments().

Applications should generally not implement a constructor. The
first place application code an run where the fragment is ready to
be used is in onAttach(Activity), the point where the fragment
is actually associated with its activity. Some applications may also
want to implement onInflate(Activity, AttributeSet, Bundle) to retrieve attributes from a
layout resource, though should take care here because this happens for
the fragment is attached to its activity.

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.

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 the Transition that will be used to move Views into the initial scene. The entering
Views will be those that are regular Views or ViewGroups that have
isTransitionGroup() return true. Typical Transitions will extend
Visibility as entering is governed by changing visibility from
INVISIBLE to VISIBLE.

Related XML Attributes

Returns

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

Returns

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

public
final
boolean
getRetainInstance()

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

Returns

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.

Related XML Attributes

Returns

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(android.transition.Transition).

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.

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.

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

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

Called by the system when the device configuration changes while your
component is running. Note that, unlike activities, other components
are never restarted when a configuration changes: they must always deal
with the results of the change, such as by re-retrieving resources.

At the time that this function has been called, your Resources
object will have been updated to return resource values matching the
new configuration.

Parameters

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

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

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

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

Parameters

savedInstanceState

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

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

See Also

Called to have the fragment instantiate its user interface view.
This is optional, and non-graphical fragments can return null (which
is the default implementation). This will be called between
onCreate(Bundle) and onActivityCreated(Bundle).

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

Parameters

inflater

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

container

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

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

Returns

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

public
void
onDestroy()

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

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
tag in a layout file. Note this is before the fragment's
onAttach(Activity) has been called; all you should do here is
parse the attributes and save them away.

This is called every time the fragment is inflated, even if it is
being inflated into a new instance with saved state. It typically makes
sense to re-parse the parameters each time, to allow them to change with
different configurations.

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

public
void
onLowMemory()

This is called when the overall system is running low on memory, and
actively running processes should trim their memory usage. While
the exact point at which this will be called is not defined, generally
it will happen when all background process have been killed.
That is, before reaching the point of killing processes hosting
service and foreground UI that we would like to avoid killing.

You should implement this method to release
any caches or other unnecessary resources you may be holding on to.
The system will perform a garbage collection for you after returning from this method.

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

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

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

Parameters

menu

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

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

public
void
onTrimMemory(int level)

Called when the operating system has determined that it is a good
time for a process to trim unneeded memory from its process. This will
happen for example when it goes in the background and there is not enough
memory to keep as many background processes running as desired. You
should never compare to exact values of the level, since new intermediate
values may be added -- you will typically want to compare if the value
is greater or equal to a level you are interested in.

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

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

Parameters

savedInstanceState

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

Parameters

See Also

public
void
setAllowEnterTransitionOverlap(boolean allow)

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

Parameters

public
void
setAllowReturnTransitionOverlap(boolean allow)

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

Parameters

Supply the construction arguments for this fragment. This can only
be called before the fragment has been attached to its activity; that
is, you should call it immediately after constructing the fragment. The
arguments supplied here will be retained across fragment destroy and
creation.

Parameters

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

Parameters

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

Parameters

public
void
setMenuVisibility(boolean menuVisible)

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

Parameters

menuVisible

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

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

Parameters

public
void
setRetainInstance(boolean retain)

Control whether a fragment instance is retained across Activity
re-creation (such as from a configuration change). This can only
be used with fragments not in the back stack. If set, the fragment
lifecycle will be slightly different when an activity is recreated:

onDestroy() will not be called (but onDetach() still
will be, because the fragment is being detached from its current activity).

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

Parameters

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

Parameters

Sets the Transition that will be used for shared elements transferred back during a
pop of the back stack. This Transition acts in the leaving Fragment.
Typical Transitions will affect size and location, such as
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(android.transition.Transition).

Parameters

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

public
void
setUserVisibleHint(boolean isVisibleToUser)

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

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

Parameters

isVisibleToUser

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

Returns a string containing a concise, human-readable description of this
object. Subclasses are encouraged to override this method and provide an
implementation that takes into account the object's type and data. The
default implementation is equivalent to the following expression: