public
class
Fragment
extends Object
implements
ComponentCallbacks2,
View.OnCreateContextMenuListener
java.lang.Object | |
↳ | android.app.Fragment |
Known Direct Subclasses |
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:
For more information about using fragments, read the Fragments developer guide.
HONEYCOMB
, a version of the API
at is also available for use on older platforms through
FragmentActivity
. See the blog post
Fragments For All 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 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.
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:
<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:
@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.
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:
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:
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:
<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 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:
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.
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:
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:
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.
Nested classes | |
---|---|
class |
Fragment.InstantiationException
Thrown by |
class |
Fragment.SavedState
State information that has been retrieved from a fragment instance
through |
XML attributes | |
---|---|
android:fragmentAllowEnterTransitionOverlap |
Sets whether the enter and exit transitions should overlap when transitioning forward. |
android:fragmentAllowReturnTransitionOverlap |
Sets whether the enter and exit transitions should overlap when transitioning because of popping the back stack. |
android:fragmentEnterTransition |
The Transition that will be used to move Views into the initial scene. |
android:fragmentExitTransition |
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. |
android:fragmentReenterTransition |
The Transition that will be used to move Views in to the scene when returning due to popping a back stack. |
android:fragmentSharedElementEnterTransition |
The Transition that will be used for shared elements transferred into the content Scene. |
android:fragmentSharedElementReturnTransition |
The Transition that will be used for shared elements transferred back during a pop of the back stack. |
Inherited constants |
---|
From
interface
android.content.ComponentCallbacks2
|
Public constructors | |
---|---|
Fragment()
Default constructor. |
Public methods | |
---|---|
void
|
dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args)
Print the Fragments's state into the given stream. |
final
boolean
|
equals(Object o)
Subclasses can not override equals(). |
final
Activity
|
getActivity()
Return the Activity this fragment is currently associated with. |
boolean
|
getAllowEnterTransitionOverlap()
Returns whether the the exit transition and enter transition overlap or not. |
boolean
|
getAllowReturnTransitionOverlap()
Returns whether the the return transition and reenter transition overlap or not. |
final
Bundle
|
getArguments()
Return the arguments supplied to |
final
FragmentManager
|
getChildFragmentManager()
Return a private FragmentManager for placing and managing Fragments inside of this Fragment. |
Context
|
getContext()
Return the |
Transition
|
getEnterTransition()
Returns the Transition that will be used to move Views into the initial scene. |
Transition
|
getExitTransition()
Returns the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack. |
final
FragmentManager
|
getFragmentManager()
Return the FragmentManager for interacting with fragments associated with this fragment's activity. |
final
Object
|
getHost()
Return the host object of this fragment. |
final
int
|
getId()
Return the identifier this fragment is known by. |
LoaderManager
|
getLoaderManager()
Return the LoaderManager for this fragment, creating it if needed. |
final
Fragment
|
getParentFragment()
Returns the parent Fragment containing this Fragment. |
Transition
|
getReenterTransition()
Returns the Transition that will be used to move Views in to the scene when returning due to popping a back stack. |
final
Resources
|
getResources()
Return |
final
boolean
|
getRetainInstance()
|
Transition
|
getReturnTransition()
Returns the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack. |
Transition
|
getSharedElementEnterTransition()
Returns the Transition that will be used for shared elements transferred into the content Scene. |
Transition
|
getSharedElementReturnTransition()
Return the Transition that will be used for shared elements transferred back during a pop of the back stack. |
final
String
|
getString(int resId, Object... formatArgs)
Return a localized formatted string from the application's package's
default string table, substituting the format arguments as defined in
|
final
String
|
getString(int resId)
Return a localized string from the application's package's default string table. |
final
String
|
getTag()
Get the tag name of the fragment, if specified. |
final
Fragment
|
getTargetFragment()
Return the target fragment set by |
final
int
|
getTargetRequestCode()
Return the target request code set by |
final
CharSequence
|
getText(int resId)
Return a localized, styled CharSequence from the application's package's default string table. |
boolean
|
getUserVisibleHint()
|
View
|
getView()
Get the root view for the fragment's layout (the one returned by |
final
int
|
hashCode()
Subclasses can not override hashCode(). |
static
Fragment
|
instantiate(Context context, String fname)
Like |
static
Fragment
|
instantiate(Context context, String fname, Bundle args)
Create a new instance of a Fragment with the given class name. |
final
boolean
|
isAdded()
Return true if the fragment is currently added to its activity. |
final
boolean
|
isDetached()
Return true if the fragment has been explicitly detached from the UI. |
final
boolean
|
isHidden()
Return true if the fragment has been hidden. |
final
boolean
|
isInLayout()
Return true if the layout is included as part of an activity view hierarchy via the <fragment> tag. |
final
boolean
|
isRemoving()
Return true if this fragment is currently being removed from its activity. |
final
boolean
|
isResumed()
Return true if the fragment is in the resumed state. |
final
boolean
|
isVisible()
Return true if the fragment is currently visible to the user. |
void
|
onActivityCreated(Bundle savedInstanceState)
Called when the fragment's activity has been created and this fragment's view hierarchy instantiated. |
void
|
onActivityResult(int requestCode, int resultCode, Intent data)
Receive the result from a previous call to
|
void
|
onAttach(Activity activity)
This method was deprecated
in API level 23.
Use |
void
|
onAttach(Context context)
Called when a fragment is first attached to its context. |
void
|
onAttachFragment(Fragment childFragment)
Called when a fragment is attached as a child of this fragment. |
void
|
onConfigurationChanged(Configuration newConfig)
Called by the system when the device configuration changes while your component is running. |
boolean
|
onContextItemSelected(MenuItem item)
This hook is called whenever an item in a context menu is selected. |
void
|
onCreate(Bundle savedInstanceState)
Called to do initial creation of a fragment. |
Animator
|
onCreateAnimator(int transit, boolean enter, int nextAnim)
Called when a fragment loads an animation. |
void
|
onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
Called when a context menu for the |
void
|
onCreateOptionsMenu(Menu menu, MenuInflater inflater)
Initialize the contents of the Activity's standard options menu. |
View
|
onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
Called to have the fragment instantiate its user interface view. |
void
|
onDestroy()
Called when the fragment is no longer in use. |
void
|
onDestroyOptionsMenu()
Called when this fragment's option menu items are no longer being included in the overall options menu. |
void
|
onDestroyView()
Called when the view previously created by |
void
|
onDetach()
Called when the fragment is no longer attached to its activity. |
void
|
onHiddenChanged(boolean hidden)
Called when the hidden state (as returned by |
void
|
onInflate(AttributeSet attrs, Bundle savedInstanceState)
This method was deprecated
in API level 12.
Use |
void
|
onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState)
This method was deprecated
in API level 23.
Use |
void
|
onInflate(Context context, AttributeSet attrs, Bundle savedInstanceState)
Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity. |
void
|
onLowMemory()
This is called when the overall system is running low on memory, and actively running processes should trim their memory usage. |
void
|
onMultiWindowModeChanged(boolean isInMultiWindowMode)
Called when the Fragment's activity changes from fullscreen mode to multi-window mode and visa-versa. |
boolean
|
onOptionsItemSelected(MenuItem item)
This hook is called whenever an item in your options menu is selected. |
void
|
onOptionsMenuClosed(Menu menu)
This hook is called whenever the options menu is being closed (either by the user canceling the menu with the back/menu button, or when an item is selected). |
void
|
onPause()
Called when the Fragment is no longer resumed. |
void
|
onPictureInPictureModeChanged(boolean isInPictureInPictureMode)
Called by the system when the activity changes to and from picture-in-picture mode. |
void
|
onPrepareOptionsMenu(Menu menu)
Prepare the Screen's standard options menu to be displayed. |
void
|
onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
Callback for the result from requesting permissions. |
void
|
onResume()
Called when the fragment is visible to the user and actively running. |
void
|
onSaveInstanceState(Bundle outState)
Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance of its process is restarted. |
void
|
onStart()
Called when the Fragment is visible to the user. |
void
|
onStop()
Called when the Fragment is no longer started. |
void
|
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. |
void
|
onViewCreated(View view, Bundle savedInstanceState)
Called immediately after |
void
|
onViewStateRestored(Bundle savedInstanceState)
Called when all saved state has been restored into the view hierarchy of the fragment. |
void
|
registerForContextMenu(View view)
Registers a context menu to be shown for the given view (multiple views can show the context menu). |
final
void
|
requestPermissions(String[] permissions, int requestCode)
Requests permissions to be granted to this application. |
void
|
setAllowEnterTransitionOverlap(boolean allow)
Sets whether the the exit transition and enter transition overlap or not. |
void
|
setAllowReturnTransitionOverlap(boolean allow)
Sets whether the the return transition and reenter transition overlap or not. |
void
|
setArguments(Bundle args)
Supply the construction arguments for this fragment. |
void
|
setEnterSharedElementCallback(SharedElementCallback callback)
When custom transitions are used with Fragments, the enter transition callback is called when this Fragment is attached or detached when not popping the back stack. |
void
|
setEnterTransition(Transition transition)
Sets the Transition that will be used to move Views into the initial scene. |
void
|
setExitSharedElementCallback(SharedElementCallback callback)
When custom transitions are used with Fragments, the exit transition callback is called when this Fragment is attached or detached when popping the back stack. |
void
|
setExitTransition(Transition transition)
Sets the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack. |
void
|
setHasOptionsMenu(boolean hasMenu)
Report that this fragment would like to participate in populating
the options menu by receiving a call to |
void
|
setInitialSavedState(Fragment.SavedState state)
Set the initial saved state that this Fragment should restore itself
from when first being constructed, as returned by
|
void
|
setMenuVisibility(boolean menuVisible)
Set a hint for whether this fragment's menu should be visible. |
void
|
setReenterTransition(Transition transition)
Sets the Transition that will be used to move Views in to the scene when returning due to popping a back stack. |
void
|
setRetainInstance(boolean retain)
Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). |
void
|
setReturnTransition(Transition transition)
Sets the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack. |
void
|
setSharedElementEnterTransition(Transition transition)
Sets the Transition that will be used for shared elements transferred into the content Scene. |
void
|
setSharedElementReturnTransition(Transition transition)
Sets the Transition that will be used for shared elements transferred back during a pop of the back stack. |
void
|
setTargetFragment(Fragment fragment, int requestCode)
Optional target for this fragment. |
void
|
setUserVisibleHint(boolean isVisibleToUser)
Set a hint to the system about whether this fragment's UI is currently visible to the user. |
boolean
|
shouldShowRequestPermissionRationale(String permission)
Gets whether you should show UI with rationale for requesting a permission. |
void
|
startActivity(Intent intent)
Call |
void
|
startActivity(Intent intent, Bundle options)
Call |
void
|
startActivityForResult(Intent intent, int requestCode)
Call |
void
|
startActivityForResult(Intent intent, int requestCode, Bundle options)
Call |
void
|
startIntentSenderForResult(IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options)
Call |
String
|
toString()
Returns a string representation of the object. |
void
|
unregisterForContextMenu(View view)
Prevents a context menu to be shown for the given view. |
Inherited methods | |
---|---|
From
class
java.lang.Object
| |
From
interface
android.content.ComponentCallbacks2
| |
From
interface
android.view.View.OnCreateContextMenuListener
| |
From
interface
android.content.ComponentCallbacks
|
Sets whether the enter and exit transitions should overlap when transitioning
forward.
Corresponds to setAllowEnterTransitionOverlap(boolean)
Must be a reference to another resource, in the form "@[+][package:]type:name
"
or to a theme attribute in the form "?[package:][type:]name
".
This corresponds to the global attribute
resource symbol fragmentAllowEnterTransitionOverlap
.
Related methods:
Sets whether the enter and exit transitions should overlap when transitioning
because of popping the back stack.
Corresponds to setAllowReturnTransitionOverlap(boolean)
Must be a reference to another resource, in the form "@[+][package:]type:name
"
or to a theme attribute in the form "?[package:][type:]name
".
This corresponds to the global attribute
resource symbol fragmentAllowReturnTransitionOverlap
.
Related methods:
The Transition that will be used to move Views into the initial scene.
Corresponds to setEnterTransition(android.transition.Transition)
Must be a reference to another resource, in the form "@[+][package:]type:name
"
or to a theme attribute in the form "?[package:][type:]name
".
This corresponds to the global attribute
resource symbol fragmentEnterTransition
.
Related methods:
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.
Corresponds to setExitTransition(android.transition.Transition)
Must be a reference to another resource, in the form "@[+][package:]type:name
"
or to a theme attribute in the form "?[package:][type:]name
".
This corresponds to the global attribute
resource symbol fragmentExitTransition
.
Related methods:
The Transition that will be used to move Views in to the scene when returning due
to popping a back stack.
Corresponds to setReenterTransition(android.transition.Transition)
Must be a reference to another resource, in the form "@[+][package:]type:name
"
or to a theme attribute in the form "?[package:][type:]name
".
This corresponds to the global attribute
resource symbol fragmentReenterTransition
.
Related methods:
The Transition that will be used for shared elements transferred into the content
Scene.
Corresponds to setSharedElementEnterTransition(android.transition.Transition)
Must be a reference to another resource, in the form "@[+][package:]type:name
"
or to a theme attribute in the form "?[package:][type:]name
".
This corresponds to the global attribute
resource symbol fragmentSharedElementEnterTransition
.
Related methods:
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.
Corresponds to setSharedElementReturnTransition(android.transition.Transition)
Must be a reference to another resource, in the form "@[+][package:]type:name
"
or to a theme attribute in the form "?[package:][type:]name
".
This corresponds to the global attribute
resource symbol fragmentSharedElementReturnTransition
.
Related methods:
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 can 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.
void dump (String prefix, FileDescriptor fd, PrintWriter writer, String[] args)
Print the Fragments's state into the given stream.
Parameters | |
---|---|
prefix |
String :
Text to print at the front of each line. |
fd |
FileDescriptor :
The raw file descriptor that the dump is being sent to. |
writer |
PrintWriter :
The PrintWriter to which you should dump your state. This will be
closed for you after you return. |
args |
String :
additional arguments to the dump request.
|
boolean equals (Object o)
Subclasses can not override equals().
Parameters | |
---|---|
o |
Object :
the reference object with which to compare. |
Returns | |
---|---|
boolean |
true if this object is the same as the obj
argument; false otherwise. |
Activity getActivity ()
Return the Activity this fragment is currently associated with.
Returns | |
---|---|
Activity |
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.
Related XML Attributes:
Returns | |
---|---|
boolean |
true when the enter transition should start as soon as possible or false to when it should wait until the exiting transition completes. |
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.
Related XML Attributes:
Returns | |
---|---|
boolean |
true to start the reenter transition when possible or false to wait until the return transition completes. |
Bundle getArguments ()
Return the arguments supplied to setArguments(Bundle)
, if any.
Returns | |
---|---|
Bundle |
FragmentManager getChildFragmentManager ()
Return a private FragmentManager for placing and managing Fragments inside of this Fragment.
Returns | |
---|---|
FragmentManager |
Context getContext ()
Return the Context
this fragment is currently associated with.
Returns | |
---|---|
Context |
Transition getEnterTransition ()
Returns the Transition that will be used to move Views into the initial scene. The entering
Views will be those that are regular Views or ViewGroups that have
isTransitionGroup()
return true. Typical Transitions will extend
Visibility
as entering is governed by changing visibility from
INVISIBLE
to VISIBLE
.
Related XML Attributes:
Returns | |
---|---|
Transition |
the Transition to use to move Views into the initial Scene. |
Transition getExitTransition ()
Returns the Transition that will be used to move Views out of the scene when the
fragment is removed, hidden, or detached when not popping the back stack.
The exiting Views will be those that are regular Views or ViewGroups that
have 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.
Related XML Attributes:
Returns | |
---|---|
Transition |
the Transition to use to move Views out of the Scene when the Fragment is being closed not due to popping the back stack. |
FragmentManager getFragmentManager ()
Return the FragmentManager for interacting with fragments associated
with this fragment's activity. Note that this will be non-null slightly
before getActivity()
, during the time from when the fragment is
placed in a FragmentTransaction
until it is committed and
attached to its activity.
If this Fragment is a child of another Fragment, the FragmentManager
returned here will be the parent's getChildFragmentManager()
.
Returns | |
---|---|
FragmentManager |
Object getHost ()
Return the host object of this fragment. May return null
if the fragment
isn't currently being hosted.
Returns | |
---|---|
Object |
int getId ()
Return the identifier this fragment is known by. This is either the android:id value supplied in a layout or the container view ID supplied when adding the fragment.
Returns | |
---|---|
int |
LoaderManager getLoaderManager ()
Return the LoaderManager for this fragment, creating it if needed.
Returns | |
---|---|
LoaderManager |
Fragment getParentFragment ()
Returns the parent Fragment containing this Fragment. If this Fragment is attached directly to an Activity, returns null.
Returns | |
---|---|
Fragment |
Transition getReenterTransition ()
Returns the Transition that will be used to move Views in to the scene when returning due
to popping a back stack. The entering Views will be those that are regular Views
or ViewGroups that have 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)
.
Related XML Attributes:
Returns | |
---|---|
Transition |
the Transition to use to move Views into the scene when reentering from a previously-started Activity. |
Resources getResources ()
Return getActivity().getResources()
.
Returns | |
---|---|
Resources |
Transition getReturnTransition ()
Returns the Transition that will be used to move Views out of the scene when the Fragment is
preparing to be removed, hidden, or detached because of popping the back stack. The exiting
Views will be those that are regular Views or ViewGroups that have
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.
Related XML Attributes:
Returns | |
---|---|
Transition |
the Transition to use to move Views out of the Scene when the Fragment is preparing to close. |
Transition getSharedElementEnterTransition ()
Returns the Transition that will be used for shared elements transferred into the content
Scene. Typical Transitions will affect size and location, such as
ChangeBounds
. A null
value will cause transferred shared elements to blink to the final position.
Related XML Attributes:
Returns | |
---|---|
Transition |
The Transition to use for shared elements transferred into the content Scene. |
Transition getSharedElementReturnTransition ()
Return the Transition that will be used for shared elements transferred back during a
pop of the back stack. This Transition acts in the leaving Fragment.
Typical Transitions will affect size and location, such as
ChangeBounds
. A null
value will cause transferred shared elements to blink to the final position.
If no value is set, the default will be to use the same value as
setSharedElementEnterTransition(android.transition.Transition)
.
Related XML Attributes:
Returns | |
---|---|
Transition |
The Transition to use for shared elements transferred out of the content Scene. |
String getString (int resId, Object... formatArgs)
Return a localized formatted string from the application's package's
default string table, substituting the format arguments as defined in
Formatter
and format(String, Object...)
.
Parameters | |
---|---|
resId |
int :
Resource id for the format string |
formatArgs |
Object :
The format arguments that will be used for substitution.
|
Returns | |
---|---|
String |
String getString (int resId)
Return a localized string from the application's package's default string table.
Parameters | |
---|---|
resId |
int :
Resource id for the string
|
Returns | |
---|---|
String |
String getTag ()
Get the tag name of the fragment, if specified.
Returns | |
---|---|
String |
Fragment getTargetFragment ()
Return the target fragment set by setTargetFragment(Fragment, int)
.
Returns | |
---|---|
Fragment |
int getTargetRequestCode ()
Return the target request code set by setTargetFragment(Fragment, int)
.
Returns | |
---|---|
int |
CharSequence getText (int resId)
Return a localized, styled CharSequence from the application's package's default string table.
Parameters | |
---|---|
resId |
int :
Resource id for the CharSequence text
|
Returns | |
---|---|
CharSequence |
boolean getUserVisibleHint ()
Returns | |
---|---|
boolean |
The current value of the user-visible hint on this fragment. |
See also:
View getView ()
Get the root view for the fragment's layout (the one returned by onCreateView(LayoutInflater, ViewGroup, Bundle)
),
if provided.
Returns | |
---|---|
View |
The fragment's root view, or null if it has no layout. |
int hashCode ()
Subclasses can not override hashCode().
Returns | |
---|---|
int |
a hash code value for this object. |
Fragment instantiate (Context context, String fname)
Like instantiate(Context, String, Bundle)
but with a null
argument Bundle.
Parameters | |
---|---|
context |
Context
|
fname |
String
|
Returns | |
---|---|
Fragment |
Fragment instantiate (Context context, String fname, Bundle args)
Create a new instance of a Fragment with the given class name. This is the same as calling its empty constructor.
Parameters | |
---|---|
context |
Context :
The calling context being used to instantiate the fragment.
This is currently just used to get its ClassLoader. |
fname |
String :
The class name of the fragment to instantiate. |
args |
Bundle :
Bundle of arguments to supply to the fragment, which it
can retrieve with getArguments() . May be null. |
Returns | |
---|---|
Fragment |
Returns a new fragment instance. |
Throws | |
---|---|
InstantiationException |
If there is a failure in instantiating the given fragment class. This is a runtime exception; it is not normally expected to happen. |
boolean isAdded ()
Return true if the fragment is currently added to its activity.
Returns | |
---|---|
boolean |
boolean isDetached ()
Return true if the fragment has been explicitly detached from the UI.
That is, FragmentTransaction.detach(Fragment)
has been used on it.
Returns | |
---|---|
boolean |
boolean isHidden ()
Return true if the fragment has been hidden. By default fragments
are shown. You can find out about changes to this state with
onHiddenChanged(boolean)
. Note that the hidden state is orthogonal
to other states -- that is, to be visible to the user, a fragment
must be both started and not hidden.
Returns | |
---|---|
boolean |
boolean isInLayout ()
Return true if the layout is included as part of an activity view hierarchy via the <fragment> tag. This will always be true when fragments are created through the <fragment> tag, except in the case where an old fragment is restored from a previous state and it does not appear in the layout of the current state.
Returns | |
---|---|
boolean |
boolean isRemoving ()
Return true if this fragment is currently being removed from its activity. This is not whether its activity is finishing, but rather whether it is in the process of being removed from its activity.
Returns | |
---|---|
boolean |
boolean isResumed ()
Return true if the fragment is in the resumed state. This is true
for the duration of onResume()
and onPause()
as well.
Returns | |
---|---|
boolean |
boolean isVisible ()
Return true if the fragment is currently visible to the user. This means it: (1) has been added, (2) has its view attached to the window, and (3) is not hidden.
Returns | |
---|---|
boolean |
void onActivityCreated (Bundle savedInstanceState)
Called when the fragment's activity has been created and this
fragment's view hierarchy instantiated. It can be used to do final
initialization once these pieces are in place, such as retrieving
views or restoring state. It is also useful for fragments that use
setRetainInstance(boolean)
to retain their instance,
as this callback tells the fragment when it is fully associated with
the new activity instance. This is called after onCreateView(LayoutInflater, ViewGroup, Bundle)
and before onViewStateRestored(Bundle)
.
Parameters | |
---|---|
savedInstanceState |
Bundle :
If the fragment is being re-created from
a previous saved state, this is the state.
|
void onActivityResult (int requestCode, int resultCode, Intent data)
Receive the result from a previous call to
startActivityForResult(Intent, int)
. This follows the
related Activity API as described there in
onActivityResult(int, int, Intent)
.
Parameters | |
---|---|
requestCode |
int :
The integer request code originally supplied to
startActivityForResult(), allowing you to identify who this
result came from. |
resultCode |
int :
The integer result code returned by the child activity
through its setResult(). |
data |
Intent :
An Intent, which can return result data to the caller
(various data can be attached to Intent "extras").
|
void onAttach (Activity activity)
This method was deprecated
in API level 23.
Use onAttach(Context)
instead.
Parameters | |
---|---|
activity |
Activity
|
void onAttach (Context context)
Called when a fragment is first attached to its context.
onCreate(Bundle)
will be called after this.
Parameters | |
---|---|
context |
Context
|
void onAttachFragment (Fragment childFragment)
Called when a fragment is attached as a child of this fragment.
This is called after the attached fragment's onAttach
and before
the attached fragment's onCreate
if the fragment has not yet had a previous
call to onCreate
.
Parameters | |
---|---|
childFragment |
Fragment :
child fragment being attached
|
void onConfigurationChanged (Configuration newConfig)
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.
For more information, read Handling Runtime Changes.
Parameters | |
---|---|
newConfig |
Configuration :
The new device configuration.
|
boolean onContextItemSelected (MenuItem item)
This hook is called whenever an item in a context menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.
Use getMenuInfo()
to get extra information set by the
View that added this menu item.
Derived classes should call through to the base class for it to perform the default menu handling.
Parameters | |
---|---|
item |
MenuItem :
The context menu item that was selected. |
Returns | |
---|---|
boolean |
boolean Return false to allow normal context menu processing to proceed, true to consume it here. |
void onCreate (Bundle savedInstanceState)
Called to do initial creation of a fragment. This is called after
onAttach(Activity)
and before
onCreateView(LayoutInflater, ViewGroup, Bundle)
, but is not called if the fragment
instance is retained across Activity re-creation (see setRetainInstance(boolean)
).
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)
.
If your app's targetSdkVersion
is 23 or lower, child fragments
being restored from the savedInstanceState are restored after onCreate
returns. When targeting N or above and running on an N or newer platform version
they are restored by Fragment.onCreate
.
Parameters | |
---|---|
savedInstanceState |
Bundle :
If the fragment is being re-created from
a previous saved state, this is the state.
|
Animator onCreateAnimator (int transit, boolean enter, int nextAnim)
Called when a fragment loads an animation.
Parameters | |
---|---|
transit |
int
|
enter |
boolean
|
nextAnim |
int
|
Returns | |
---|---|
Animator |
void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
Called when a context menu for the view
is about to be shown.
Unlike onCreateOptionsMenu(Menu, MenuInflater)
, this will be called every
time the context menu is about to be shown and should be populated for
the view (or item inside the view for AdapterView
subclasses,
this can be found in the menuInfo
)).
Use onContextItemSelected(android.view.MenuItem)
to know when an
item has been selected.
The default implementation calls up to
Activity.onCreateContextMenu
, though
you can not call this implementation if you don't want that behavior.
It is not safe to hold onto the context menu after this method returns. Called when the context menu for this view is being built. It is not safe to hold onto the menu after this method returns.
Parameters | |
---|---|
menu |
ContextMenu :
The context menu that is being built |
v |
View :
The view for which the context menu is being built |
menuInfo |
ContextMenu.ContextMenuInfo :
Extra information about the item for which the
context menu should be shown. This information will vary
depending on the class of v.
|
void onCreateOptionsMenu (Menu menu, MenuInflater inflater)
Initialize the contents of the Activity's standard options menu. You
should place your menu items in to menu. For this method
to be called, you must have first called setHasOptionsMenu(boolean)
. See
Activity.onCreateOptionsMenu
for more information.
Parameters | |
---|---|
menu |
Menu :
The options menu in which you place your items. |
inflater |
MenuInflater
|
View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
Called to have the fragment instantiate its user interface view.
This is optional, and non-graphical fragments can return null (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 |
LayoutInflater :
The LayoutInflater object that can be used to inflate
any views in the fragment, |
container |
ViewGroup :
If non-null, this is the parent view that the fragment's
UI should be attached to. The fragment should not add the view itself,
but this can be used to generate the LayoutParams of the view. |
savedInstanceState |
Bundle :
If non-null, this fragment is being re-constructed
from a previous saved state as given here. |
Returns | |
---|---|
View |
Return the View for the fragment's UI, or null. |
void onDestroy ()
Called when the fragment is no longer in use. This is called
after onStop()
and before onDetach()
.
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).
void onDestroyView ()
Called when the view previously created by onCreateView(LayoutInflater, ViewGroup, Bundle)
has
been detached from the fragment. The next time the fragment needs
to be displayed, a new view will be created. This is called
after onStop()
and before onDestroy()
. It is called
regardless of whether onCreateView(LayoutInflater, ViewGroup, Bundle)
returned a
non-null view. Internally it is called after the view's state has
been saved but before it has been removed from its parent.
void onDetach ()
Called when the fragment is no longer attached to its activity. This is called after
onDestroy()
, except in the cases where the fragment instance is retained across
Activity re-creation (see setRetainInstance(boolean)
), in which case it is called
after onStop()
.
void onHiddenChanged (boolean hidden)
Called when the hidden state (as returned by isHidden()
of
the fragment has changed. Fragments start out not hidden; this will
be called whenever the fragment changes state from that.
Parameters | |
---|---|
hidden |
boolean :
True if the fragment is now hidden, false if it is not
visible.
|
void onInflate (AttributeSet attrs, Bundle savedInstanceState)
This method was deprecated
in API level 12.
Use onInflate(Context, AttributeSet, Bundle)
instead.
Parameters | |
---|---|
attrs |
AttributeSet
|
savedInstanceState |
Bundle
|
void onInflate (Activity activity, AttributeSet attrs, Bundle savedInstanceState)
This method was deprecated
in API level 23.
Use onInflate(Context, AttributeSet, Bundle)
instead.
Parameters | |
---|---|
activity |
Activity
|
attrs |
AttributeSet
|
savedInstanceState |
Bundle
|
void onInflate (Context context, AttributeSet attrs, Bundle savedInstanceState)
Called when a fragment is being created as part of a view layout
inflation, typically from setting the content view of an activity. This
may be called immediately after the fragment is created from a 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 Note that parsing the XML attributes uses a "styleable" resource. The
declaration for the styleable used here is: The fragment can then be declared within its activity's content layout
through a tag like this: This fragment can also be created dynamically from arguments given
at runtime in the arguments Bundle; here is an example of doing so at
creation of the containing activity:onAttach(Activity)
has been called; all you should do here is
parse the attributes and save them away.
getArguments()
:public static class MyFragment extends Fragment {
CharSequence mLabel;
/**
* Create a new instance of MyFragment that will be initialized
* with the given arguments.
*/
static MyFragment newInstance(CharSequence label) {
MyFragment f = new MyFragment();
Bundle b = new Bundle();
b.putCharSequence("label", label);
f.setArguments(b);
return f;
}
/**
* Parse attributes during inflation from a view hierarchy into the
* arguments we handle.
*/
@Override public void onInflate(Activity activity, AttributeSet attrs,
Bundle savedInstanceState) {
super.onInflate(activity, attrs, savedInstanceState);
TypedArray a = activity.obtainStyledAttributes(attrs,
R.styleable.FragmentArguments);
mLabel = a.getText(R.styleable.FragmentArguments_android_label);
a.recycle();
}
/**
* During creation, if arguments have been supplied to the fragment
* then parse those out.
*/
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
mLabel = args.getCharSequence("label", mLabel);
}
}
/**
* Create the view for this fragment, using the arguments given to it.
*/
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_world, container, false);
View tv = v.findViewById(R.id.text);
((TextView)tv).setText(mLabel != null ? mLabel : "(no label)");
tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
return v;
}
}
<declare-styleable name="FragmentArguments">
<attr name="android:label" />
</declare-styleable>
<fragment class="com.example.android.apis.app.FragmentArguments$MyFragment"
android:id="@+id/embedded"
android:layout_width="0px" android:layout_height="wrap_content"
android:layout_weight="1"
android:label="@string/fragment_arguments_embedded" />
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_arguments);
if (savedInstanceState == null) {
// First-time init; create fragment to embed in activity.
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment newFragment = MyFragment.newInstance("From Arguments");
ft.add(R.id.created, newFragment);
ft.commit();
}
}
Parameters | |
---|---|
context |
Context :
The Context that is inflating this fragment. |
attrs |
AttributeSet :
The attributes at the tag where the fragment is
being created. |
savedInstanceState |
Bundle :
If the fragment is being re-created from
a previous saved state, this is the state.
|
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.
Preferably, you should implement onTrimMemory(int)
from
ComponentCallbacks2
to incrementally unload your resources based on various
levels of memory demands. That API is available for API level 14 and higher, so you should
only use this onLowMemory()
method as a fallback for older versions, which can be
treated the same as onTrimMemory(int)
with the TRIM_MEMORY_COMPLETE
level.
void onMultiWindowModeChanged (boolean isInMultiWindowMode)
Called when the Fragment's activity changes from fullscreen mode to multi-window mode and
visa-versa. This is generally tied to onMultiWindowModeChanged(boolean)
of the
containing Activity.
Parameters | |
---|---|
isInMultiWindowMode |
boolean :
True if the activity is in multi-window mode.
|
boolean onOptionsItemSelected (MenuItem item)
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.
Parameters | |
---|---|
item |
MenuItem :
The menu item that was selected. |
Returns | |
---|---|
boolean |
boolean Return false to allow normal menu processing to proceed, true to consume it here. |
See also:
void onOptionsMenuClosed (Menu menu)
This hook is called whenever the options menu is being closed (either by the user canceling the menu with the back/menu button, or when an item is selected).
Parameters | |
---|---|
menu |
Menu :
The options menu as last shown or first initialized by
onCreateOptionsMenu().
|
void onPause ()
Called when the Fragment is no longer resumed. This is generally
tied to Activity.onPause
of the containing
Activity's lifecycle.
void onPictureInPictureModeChanged (boolean isInPictureInPictureMode)
Called by the system when the activity changes to and from picture-in-picture mode. This is
generally tied to onPictureInPictureModeChanged(boolean)
of the containing Activity.
Parameters | |
---|---|
isInPictureInPictureMode |
boolean :
True if the activity is in picture-in-picture mode.
|
void onPrepareOptionsMenu (Menu menu)
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 |
Menu :
The options menu as last shown or first initialized by
onCreateOptionsMenu(). |
void onRequestPermissionsResult (int requestCode, String[] permissions, int[] grantResults)
Callback for the result from requesting permissions. This method
is invoked for every call on requestPermissions(String[], int)
.
Note: It is possible that the permissions request interaction with the user is interrupted. In this case you will receive empty permissions and results arrays which should be treated as a cancellation.
Parameters | |
---|---|
requestCode |
int :
The request code passed in requestPermissions(String[], int) . |
permissions |
String :
The requested permissions. Never null. |
grantResults |
int :
The grant results for the corresponding permissions
which is either PERMISSION_GRANTED
or PERMISSION_DENIED . Never null. |
See also:
void onResume ()
Called when the fragment is visible to the user and actively running.
This is generally
tied to Activity.onResume
of the containing
Activity's lifecycle.
void onSaveInstanceState (Bundle outState)
Called to ask the fragment to save its current dynamic state, so it
can later be reconstructed in a new instance of its process is
restarted. If a new instance of the fragment later needs to be
created, the data you place in the Bundle here will be available
in the Bundle given to onCreate(Bundle)
,
onCreateView(LayoutInflater, ViewGroup, Bundle)
, and
onActivityCreated(Bundle)
.
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.
Parameters | |
---|---|
outState |
Bundle :
Bundle in which to place your saved state.
|
void onStart ()
Called when the Fragment is visible to the user. This is generally
tied to Activity.onStart
of the containing
Activity's lifecycle.
void onStop ()
Called when the Fragment is no longer started. This is generally
tied to Activity.onStop
of the containing
Activity's lifecycle.
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.
To retrieve the processes current trim level at any point, you can
use ActivityManager.getMyMemoryState(RunningAppProcessInfo)
.
Parameters | |
---|---|
level |
int :
The context of the trim, giving a hint of the amount of
trimming the application may like to perform. May be
TRIM_MEMORY_COMPLETE , TRIM_MEMORY_MODERATE ,
TRIM_MEMORY_BACKGROUND , TRIM_MEMORY_UI_HIDDEN ,
TRIM_MEMORY_RUNNING_CRITICAL , TRIM_MEMORY_RUNNING_LOW ,
or TRIM_MEMORY_RUNNING_MODERATE .
|
void onViewCreated (View view, Bundle savedInstanceState)
Called immediately after onCreateView(LayoutInflater, ViewGroup, Bundle)
has returned, but before any saved state has been restored in to the view.
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.
Parameters | |
---|---|
view |
View :
The View returned by onCreateView(LayoutInflater, ViewGroup, Bundle) . |
savedInstanceState |
Bundle :
If non-null, this fragment is being re-constructed
from a previous saved state as given here.
|
void onViewStateRestored (Bundle savedInstanceState)
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 |
Bundle :
If the fragment is being re-created from
a previous saved state, this is the state.
|
void registerForContextMenu (View view)
Registers a context menu to be shown for the given view (multiple views
can show the context menu). This method will set the
View.OnCreateContextMenuListener
on the view to this fragment, so
onCreateContextMenu(ContextMenu, View, ContextMenuInfo)
will be
called when it is time to show the context menu.
Parameters | |
---|---|
view |
View :
The view that should show a context menu.
|
See also:
void requestPermissions (String[] permissions, int requestCode)
Requests permissions to be granted to this application. These permissions
must be requested in your manifest, they should not be granted to your app,
and they should have protection level #PROTECTION_DANGEROUS dangerous
, regardless whether they are declared by
the platform or a third-party app.
Normal permissions PROTECTION_NORMAL
are granted at install time if requested in the manifest. Signature permissions
PROTECTION_SIGNATURE
are granted at
install time if requested in the manifest and the signature of your app matches
the signature of the app declaring the permissions.
If your app does not have the requested permissions the user will be presented
with UI for accepting them. After the user has accepted or rejected the
requested permissions you will receive a callback on onRequestPermissionsResult(int, String[], int[])
reporting whether the
permissions were granted or not.
Note that requesting a permission does not guarantee it will be granted and your app should be able to run without having this permission.
This method may start an activity allowing the user to choose which permissions
to grant and which to reject. Hence, you should be prepared that your activity
may be paused and resumed. Further, granting some permissions may require
a restart of you application. In such a case, the system will recreate the
activity stack before delivering the result to onRequestPermissionsResult(int, String[], int[])
.
When checking whether you have a permission you should use checkSelfPermission(String)
.
Calling this API for permissions already granted to your app would show UI to the user to decide whether the app can still hold these permissions. This can be useful if the way your app uses data guarded by the permissions changes significantly.
You cannot request a permission if your activity sets noHistory
to
true
because in this case the activity would not receive
result callbacks including onRequestPermissionsResult(int, String[], int[])
.
A sample permissions request looks like this:
private void showContacts() {
if (getActivity().checkSelfPermission(Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},
PERMISSIONS_REQUEST_READ_CONTACTS);
} else {
doShowContacts();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
doShowContacts();
}
}
Parameters | |
---|---|
permissions |
String :
The requested permissions. Must me non-null and not empty. |
requestCode |
int :
Application specific request code to match with a result
reported to onRequestPermissionsResult(int, String[], int[]) .
Should be >= 0. |
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.
Related XML Attributes:
Parameters | |
---|---|
allow |
boolean :
true to start the enter transition when possible or false to
wait until the exiting transition completes. |
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.
Related XML Attributes:
Parameters | |
---|---|
allow |
boolean :
true to start the reenter transition when possible or false to wait until the
return transition completes. |
void setArguments (Bundle args)
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 | |
---|---|
args |
Bundle
|
void setEnterSharedElementCallback (SharedElementCallback callback)
When custom transitions are used with Fragments, the enter transition callback is called when this Fragment is attached or detached when not popping the back stack.
Parameters | |
---|---|
callback |
SharedElementCallback :
Used to manipulate the shared element transitions on this Fragment
when added not as a pop from the back stack.
|
void setEnterTransition (Transition transition)
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.
Related XML Attributes:
Parameters | |
---|---|
transition |
Transition :
The Transition to use to move Views into the initial Scene. |
void setExitSharedElementCallback (SharedElementCallback callback)
When custom transitions are used with Fragments, the exit transition callback is called when this Fragment is attached or detached when popping the back stack.
Parameters | |
---|---|
callback |
SharedElementCallback :
Used to manipulate the shared element transitions on this Fragment
when added as a pop from the back stack.
|
void setExitTransition (Transition transition)
Sets the Transition that will be used to move Views out of the scene when the
fragment is removed, hidden, or detached when not popping the back stack.
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.
Related XML Attributes:
Parameters | |
---|---|
transition |
Transition :
The Transition to use to move Views out of the Scene when the Fragment
is being closed not due to popping the back stack. |
void setHasOptionsMenu (boolean hasMenu)
Report that this fragment would like to participate in populating
the options menu by receiving a call to onCreateOptionsMenu(Menu, MenuInflater)
and related methods.
Parameters | |
---|---|
hasMenu |
boolean :
If true, the fragment has menu items to contribute.
|
void setInitialSavedState (Fragment.SavedState state)
Set the initial saved state that this Fragment should restore itself
from when first being constructed, as returned by
FragmentManager.saveFragmentInstanceState
.
Parameters | |
---|---|
state |
Fragment.SavedState :
The state the fragment should be restored from.
|
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 |
boolean :
The default is true, meaning the fragment's menu will
be shown as usual. If false, the user will not see the menu.
|
void setReenterTransition (Transition transition)
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)
.
Related XML Attributes:
Parameters | |
---|---|
transition |
Transition :
The Transition to use to move Views into the scene when reentering from a
previously-started Activity. |
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).
onCreate(Bundle)
will not be called since the fragment
is not being re-created.
onAttach(Activity)
and onActivityCreated(Bundle)
will
still be called.
Parameters | |
---|---|
retain |
boolean
|
void setReturnTransition (Transition transition)
Sets the Transition that will be used to move Views out of the scene when the Fragment is
preparing to be removed, hidden, or detached because of popping the back stack. 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)
.
Related XML Attributes:
Parameters | |
---|---|
transition |
Transition :
The Transition to use to move Views out of the Scene when the Fragment
is preparing to close. |
void setSharedElementEnterTransition (Transition transition)
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.
Related XML Attributes:
Parameters | |
---|---|
transition |
Transition :
The Transition to use for shared elements transferred into the content
Scene. |
void setSharedElementReturnTransition (Transition transition)
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)
.
Related XML Attributes:
Parameters | |
---|---|
transition |
Transition :
The Transition to use for shared elements transferred out of the content
Scene. |
void setTargetFragment (Fragment fragment, int requestCode)
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()
.
Parameters | |
---|---|
fragment |
Fragment :
The fragment that is the target of this one. |
requestCode |
int :
Optional request code, for convenience if you
are going to call back with onActivityResult(int, int, Intent) .
|
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.
Note: Prior to Android N there was a platform bug that could cause
setUserVisibleHint
to bring a fragment up to the started state before its
FragmentTransaction
had been committed. As some apps relied on this behavior,
it is preserved for apps that declare a targetSdkVersion
of 23 or lower.
Parameters | |
---|---|
isVisibleToUser |
boolean :
true if this fragment's UI is currently visible to the user (default),
false if it is not.
|
boolean shouldShowRequestPermissionRationale (String permission)
Gets whether you should show UI with rationale for requesting a permission. You should do this only if you do not have the permission and the context in which the permission is requested does not clearly communicate to the user what would be the benefit from granting this permission.
For example, if you write a camera app, requesting the camera permission would be expected by the user and no rationale for why it is requested is needed. If however, the app needs location for tagging photos then a non-tech savvy user may wonder how location is related to taking photos. In this case you may choose to show UI with rationale of requesting this permission.
Parameters | |
---|---|
permission |
String :
A permission your app wants to request. |
Returns | |
---|---|
boolean |
Whether you can show permission rationale UI. |
void startActivity (Intent intent)
Call startActivity(Intent)
from the fragment's
containing Activity.
Parameters | |
---|---|
intent |
Intent :
The intent to start.
|
void startActivity (Intent intent, Bundle options)
Call startActivity(Intent, Bundle)
from the fragment's
containing Activity.
Parameters | |
---|---|
intent |
Intent :
The intent to start. |
options |
Bundle :
Additional options for how the Activity should be started.
See Context.startActivity(Intent, Bundle) for more details.
|
void startActivityForResult (Intent intent, int requestCode)
Call startActivityForResult(Intent, int)
from the fragment's
containing Activity.
Parameters | |
---|---|
intent |
Intent
|
requestCode |
int
|
void startActivityForResult (Intent intent, int requestCode, Bundle options)
Call startActivityForResult(Intent, int, Bundle)
from the fragment's
containing Activity.
Parameters | |
---|---|
intent |
Intent
|
requestCode |
int
|
options |
Bundle
|
void startIntentSenderForResult (IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options)
Call startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)
from the fragment's containing Activity.
Parameters | |
---|---|
intent |
IntentSender
|
requestCode |
int
|
fillInIntent |
Intent
|
flagsMask |
int
|
flagsValues |
int
|
extraFlags |
int
|
options |
Bundle
|
Throws | |
---|---|
IntentSender.SendIntentException |
String toString ()
Returns a string representation of the object. In general, the
toString
method returns a string that
"textually represents" this object. The result should
be a concise but informative representation that is easy for a
person to read.
It is recommended that all subclasses override this method.
The toString
method for class Object
returns a string consisting of the name of the class of which the
object is an instance, the at-sign character `@
', and
the unsigned hexadecimal representation of the hash code of the
object. In other words, this method returns a string equal to the
value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Returns | |
---|---|
String |
a string representation of the object. |
void unregisterForContextMenu (View view)
Prevents a context menu to be shown for the given view. This method will
remove the View.OnCreateContextMenuListener
on the view.
Parameters | |
---|---|
view |
View :
The view that should stop showing a context menu.
|
See also: