public class Fragment extends Object implements ComponentCallbacks2, View.OnCreateContextMenuListener
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.
Build.VERSION_CODES.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(android.content.Context)
called once the fragment is associated with its activity.
onCreate(android.os.Bundle)
called to do initial creation of the fragment.
onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
creates and returns the view hierarchy associated
with the fragment.
onActivityCreated(android.os.Bundle)
tells the fragment that its activity has
completed its own Activity.onCreate()
.
onViewStateRestored(android.os.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:
The layout is installed in the activity in the normal way:
The titles fragment, showing a list of titles, is fairly simple, relying
on ListFragment
for most of its work. Note the implementation of
clicking an item: depending on the current activity's layout, it can either
create and display a new fragment to show the details in-place (more about
this later), or start a new activity to show the details.
The details fragment showing the contents of a selected item just displays a string of text based on an index of a string array built in to the app:
In this case when the user clicks on a title, there is no details container in the current activity, so the titles fragment's click code will launch a new activity to display the details fragment:
However the screen may be large enough to show both the list of titles and details about the currently selected title. To use such a layout on a landscape screen, this alternative layout can be placed under layout-land:
Note how the prior code will adjust to this alternative UI flow: the titles fragment will now embed the details fragment inside of this activity, and the details activity will finish itself if it is running in a configuration where the details can be shown in-place.
When a configuration change causes the activity hosting these fragments
to restart, its new instance may use a different layout that doesn't
include the same fragments as the previous layout. In this case all of
the previous fragments will still be instantiated and running in the new
instance. However, any that are no longer associated with a <fragment>
tag in the view hierarchy will not have their content view created
and will return false from isInLayout()
. (The code here also shows
how you can determine if a fragment placed in a container is no longer
running in a layout with that container and avoid creating its view hierarchy
in that case.)
The attributes of the <fragment> tag are used to control the
LayoutParams provided when attaching the fragment's view to the parent
container. They can also be parsed by the fragment in onInflate(android.util.AttributeSet, android.os.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:
A function that creates a new instance of the fragment, replacing whatever current fragment instance is being shown and pushing that change on to the back stack could be written as:
After each call to this function, a new entry is on the stack, and pressing back will pop it to return the user to whatever previous state the activity UI was in.
Modifier and Type | Class and Description |
---|---|
static class |
Fragment.InstantiationException
Thrown by
instantiate(Context, String, Bundle) when
there is an instantiation failure. |
static class |
Fragment.SavedState
State information that has been retrieved from a fragment instance
through
FragmentManager.saveFragmentInstanceState . |
TRIM_MEMORY_BACKGROUND, TRIM_MEMORY_COMPLETE, TRIM_MEMORY_MODERATE, TRIM_MEMORY_RUNNING_CRITICAL, TRIM_MEMORY_RUNNING_LOW, TRIM_MEMORY_RUNNING_MODERATE, TRIM_MEMORY_UI_HIDDEN
Constructor and Description |
---|
Fragment()
Default constructor.
|
Modifier and Type | Method and Description |
---|---|
void |
dump(String prefix,
FileDescriptor fd,
PrintWriter writer,
String[] args)
Print the Fragments's state into the given stream.
|
boolean |
equals(Object o)
Subclasses can not override equals().
|
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.
|
Bundle |
getArguments()
Return the arguments supplied to
setArguments(android.os.Bundle) , if any. |
FragmentManager |
getChildFragmentManager()
Return a private FragmentManager for placing and managing Fragments
inside of this Fragment.
|
Context |
getContext()
Return the
Context this fragment is currently associated with. |
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.
|
FragmentManager |
getFragmentManager()
Return the FragmentManager for interacting with fragments associated
with this fragment's activity.
|
Object |
getHost()
Return the host object of this fragment.
|
int |
getId()
Return the identifier this fragment is known by.
|
LayoutInflater |
getLayoutInflater(Bundle savedInstanceState) |
LoaderManager |
getLoaderManager()
Return the LoaderManager for this fragment, creating it if needed.
|
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.
|
Resources |
getResources()
Return
getActivity().getResources() . |
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.
|
String |
getString(int resId)
Return a localized string from the application's package's
default string table.
|
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 String.format(java.lang.String, java.lang.Object...) . |
String |
getTag()
Get the tag name of the fragment, if specified.
|
Fragment |
getTargetFragment()
Return the target fragment set by
setTargetFragment(android.app.Fragment, int) . |
int |
getTargetRequestCode()
Return the target request code set by
setTargetFragment(android.app.Fragment, int) . |
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
onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) ),
if provided. |
int |
hashCode()
Subclasses can not override hashCode().
|
static Fragment |
instantiate(Context context,
String fname)
Like
instantiate(Context, String, Bundle) but with a null
argument Bundle. |
static Fragment |
instantiate(Context context,
String fname,
Bundle args)
Create a new instance of a Fragment with the given class name.
|
boolean |
isAdded()
Return true if the fragment is currently added to its activity.
|
boolean |
isDetached()
Return true if the fragment has been explicitly detached from the UI.
|
boolean |
isHidden()
Return true if the fragment has been hidden.
|
boolean |
isInLayout()
Return true if the layout is included as part of an activity view
hierarchy via the <fragment> tag.
|
boolean |
isRemoving()
Return true if this fragment is currently being removed from its
activity.
|
boolean |
isResumed()
Return true if the fragment is in the resumed state.
|
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
startActivityForResult(Intent, int) . |
void |
onAttach(Activity activity)
Deprecated.
Use
onAttach(Context) instead. |
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
view is about to be shown. |
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
onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) has
been detached from the fragment. |
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
isHidden() of
the fragment has changed. |
void |
onInflate(Activity activity,
AttributeSet attrs,
Bundle savedInstanceState)
Deprecated.
Use
onInflate(Context, AttributeSet, Bundle) instead. |
void |
onInflate(AttributeSet attrs,
Bundle savedInstanceState)
Deprecated.
Use
onInflate(Context, AttributeSet, Bundle) instead. |
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
onCreateView(LayoutInflater, ViewGroup, Bundle)
has returned, but before any saved state has been restored in to the view. |
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).
|
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 |
setEnterSharedElementTransitionCallback(SharedElementCallback callback) |
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 |
setExitSharedElementTransitionCallback(SharedElementCallback callback) |
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
onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater)
and related methods. |
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 . |
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
Activity.startActivity(Intent) from the fragment's
containing Activity. |
void |
startActivity(Intent intent,
Bundle options)
Call
Activity.startActivity(Intent, Bundle) from the fragment's
containing Activity. |
void |
startActivityForResult(Intent intent,
int requestCode)
Call
Activity.startActivityForResult(Intent, int) from the fragment's
containing Activity. |
void |
startActivityForResult(Intent intent,
int requestCode,
Bundle options)
Call
Activity.startActivityForResult(Intent, int, Bundle) from the fragment's
containing Activity. |
void |
startIntentSenderForResult(IntentSender intent,
int requestCode,
Intent fillInIntent,
int flagsMask,
int flagsValues,
int extraFlags,
Bundle options)
Call
Activity.startIntentSenderForResult(IntentSender, int, Intent, int, int, int,
Bundle) from the fragment's containing Activity. |
String |
toString()
Returns a string representation of the object.
|
void |
unregisterForContextMenu(View view)
Prevents a context menu to be shown for the given view.
|
public Fragment()
setArguments(android.os.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(android.util.AttributeSet, android.os.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 static Fragment instantiate(Context context, String fname)
instantiate(Context, String, Bundle)
but with a null
argument Bundle.public static Fragment instantiate(Context context, String fname, Bundle args)
context
- The calling context being used to instantiate the fragment.
This is currently just used to get its ClassLoader.fname
- The class name of the fragment to instantiate.args
- Bundle of arguments to supply to the fragment, which it
can retrieve with getArguments()
. May be null.InstantiationException
- If there is a failure in instantiating
the given fragment class. This is a runtime exception; it is not
normally expected to happen.public final boolean equals(Object o)
equals
in class Object
o
- the reference object with which to compare.true
if this object is the same as the obj
argument; false
otherwise.Object.hashCode()
,
HashMap
public final int hashCode()
hashCode
in class Object
Object.equals(java.lang.Object)
,
System.identityHashCode(java.lang.Object)
public String toString()
Object
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())
public final int getId()
public final String getTag()
public void setArguments(Bundle args)
public final Bundle getArguments()
setArguments(android.os.Bundle)
, if any.public void setInitialSavedState(Fragment.SavedState state)
FragmentManager.saveFragmentInstanceState
.state
- The state the fragment should be restored from.public void setTargetFragment(Fragment fragment, int requestCode)
FragmentManager.putFragment()
.fragment
- The fragment that is the target of this one.requestCode
- Optional request code, for convenience if you
are going to call back with onActivityResult(int, int, Intent)
.public final Fragment getTargetFragment()
setTargetFragment(android.app.Fragment, int)
.public final int getTargetRequestCode()
setTargetFragment(android.app.Fragment, int)
.public Context getContext()
Context
this fragment is currently associated with.public final Activity getActivity()
public final Object getHost()
null
if the fragment
isn't currently being hosted.public final Resources getResources()
getActivity().getResources()
.public final CharSequence getText(@StringRes int resId)
resId
- Resource id for the CharSequence textpublic final String getString(@StringRes int resId)
resId
- Resource id for the stringpublic final String getString(@StringRes int resId, Object... formatArgs)
Formatter
and String.format(java.lang.String, java.lang.Object...)
.resId
- Resource id for the format stringformatArgs
- The format arguments that will be used for substitution.public final FragmentManager getFragmentManager()
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()
.
public final FragmentManager getChildFragmentManager()
public final Fragment getParentFragment()
public final boolean isAdded()
public final boolean isDetached()
FragmentTransaction.detach(Fragment)
has been used on it.public final boolean isRemoving()
public final boolean isInLayout()
public final boolean isResumed()
onResume()
and onPause()
as well.public final boolean isVisible()
public final boolean isHidden()
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 void onHiddenChanged(boolean hidden)
isHidden()
of
the fragment has changed. Fragments start out not hidden; this will
be called whenever the fragment changes state from that.hidden
- True if the fragment is now hidden, false if it is not
visible.public void setRetainInstance(boolean retain)
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.
public final boolean getRetainInstance()
public void setHasOptionsMenu(boolean hasMenu)
onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater)
and related methods.hasMenu
- If true, the fragment has menu items to contribute.public void setMenuVisibility(boolean menuVisible)
menuVisible
- The default is true, meaning the fragment's menu will
be shown as usual. If false, the user will not see the menu.public void setUserVisibleHint(boolean isVisibleToUser)
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.
isVisibleToUser
- true if this fragment's UI is currently visible to the user (default),
false if it is not.public boolean getUserVisibleHint()
setUserVisibleHint(boolean)
public LoaderManager getLoaderManager()
public void startActivity(Intent intent)
Activity.startActivity(Intent)
from the fragment's
containing Activity.intent
- The intent to start.public void startActivity(Intent intent, Bundle options)
Activity.startActivity(Intent, Bundle)
from the fragment's
containing Activity.intent
- The intent to start.options
- Additional options for how the Activity should be started.
See Context.startActivity(Intent, Bundle)
for more details.public void startActivityForResult(Intent intent, int requestCode)
Activity.startActivityForResult(Intent, int)
from the fragment's
containing Activity.public void startActivityForResult(Intent intent, int requestCode, Bundle options)
Activity.startActivityForResult(Intent, int, Bundle)
from the fragment's
containing Activity.public void startIntentSenderForResult(IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) throws IntentSender.SendIntentException
Activity.startIntentSenderForResult(IntentSender, int, Intent, int, int, int,
Bundle)
from the fragment's containing Activity.IntentSender.SendIntentException
public void onActivityResult(int requestCode, int resultCode, Intent data)
startActivityForResult(Intent, int)
. This follows the
related Activity API as described there in
Activity.onActivityResult(int, int, Intent)
.requestCode
- The integer request code originally supplied to
startActivityForResult(), allowing you to identify who this
result came from.resultCode
- The integer result code returned by the child activity
through its setResult().data
- An Intent, which can return result data to the caller
(various data can be attached to Intent "extras").public final void requestPermissions(String[] permissions, int requestCode)
#PROTECTION_DANGEROUS dangerous
, regardless whether they are declared by
the platform or a third-party app.
Normal permissions PermissionInfo.PROTECTION_NORMAL
are granted at install time if requested in the manifest. Signature permissions
PermissionInfo.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 Context.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();
}
}
permissions
- The requested permissions. Must me non-null and not empty.requestCode
- Application specific request code to match with a result
reported to onRequestPermissionsResult(int, String[], int[])
.
Should be >= 0.onRequestPermissionsResult(int, String[], int[])
,
Context.checkSelfPermission(String)
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
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.
requestCode
- The request code passed in requestPermissions(String[], int)
.permissions
- The requested permissions. Never null.grantResults
- The grant results for the corresponding permissions
which is either PackageManager.PERMISSION_GRANTED
or PackageManager.PERMISSION_DENIED
. Never null.requestPermissions(String[], int)
public boolean shouldShowRequestPermissionRationale(String 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.
permission
- A permission your app wants to request.Context.checkSelfPermission(String)
,
requestPermissions(String[], int)
,
onRequestPermissionsResult(int, String[], int[])
public LayoutInflater getLayoutInflater(Bundle savedInstanceState)
@Deprecated public void onInflate(AttributeSet attrs, Bundle savedInstanceState)
onInflate(Context, AttributeSet, Bundle)
instead.public void onInflate(Context context, AttributeSet attrs, Bundle savedInstanceState)
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()
:
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:
context
- The Context that is inflating this fragment.attrs
- The attributes at the tag where the fragment is
being created.savedInstanceState
- If the fragment is being re-created from
a previous saved state, this is the state.@Deprecated public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState)
onInflate(Context, AttributeSet, Bundle)
instead.public void onAttachFragment(Fragment childFragment)
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
.
childFragment
- child fragment being attachedpublic void onAttach(Context context)
onCreate(Bundle)
will be called after this.@Deprecated public void onAttach(Activity activity)
onAttach(Context)
instead.public Animator onCreateAnimator(int transit, boolean enter, int nextAnim)
public void onCreate(Bundle savedInstanceState)
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 Build.VERSION_CODES.M
or lower, child fragments being restored from the savedInstanceState are restored after
onCreate
returns. When targeting Build.VERSION_CODES.N
or
above and running on an N or newer platform version
they are restored by Fragment.onCreate
.
savedInstanceState
- If the fragment is being re-created from
a previous saved state, this is the state.public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
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.
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.public void onViewCreated(View view, Bundle savedInstanceState)
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.view
- The View returned by onCreateView(LayoutInflater, ViewGroup, Bundle)
.savedInstanceState
- If non-null, this fragment is being re-constructed
from a previous saved state as given here.public View getView()
onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
),
if provided.public void onActivityCreated(Bundle savedInstanceState)
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(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
and before onViewStateRestored(Bundle)
.savedInstanceState
- If the fragment is being re-created from
a previous saved state, this is the state.public void onViewStateRestored(Bundle savedInstanceState)
onActivityCreated(Bundle)
and before
onStart()
.savedInstanceState
- If the fragment is being re-created from
a previous saved state, this is the state.public void onStart()
Activity.onStart
of the containing
Activity's lifecycle.public void onResume()
Activity.onResume
of the containing
Activity's lifecycle.public void onSaveInstanceState(Bundle outState)
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.
outState
- Bundle in which to place your saved state.public void onMultiWindowModeChanged(boolean isInMultiWindowMode)
Activity.onMultiWindowModeChanged(boolean)
of the
containing Activity.isInMultiWindowMode
- True if the activity is in multi-window mode.public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode)
Activity.onPictureInPictureModeChanged(boolean)
of the containing Activity.isInPictureInPictureMode
- True if the activity is in picture-in-picture mode.public void onConfigurationChanged(Configuration newConfig)
ComponentCallbacks
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.
onConfigurationChanged
in interface ComponentCallbacks
newConfig
- The new device configuration.public void onPause()
Activity.onPause
of the containing
Activity's lifecycle.public void onStop()
Activity.onStop
of the containing
Activity's lifecycle.public void onLowMemory()
ComponentCallbacks
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 ComponentCallbacks2.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 ComponentCallbacks.onLowMemory()
method as a fallback for older versions, which can be
treated the same as ComponentCallbacks2.onTrimMemory(int)
with the ComponentCallbacks2.TRIM_MEMORY_COMPLETE
level.
onLowMemory
in interface ComponentCallbacks
public void onTrimMemory(int level)
ComponentCallbacks2
To retrieve the processes current trim level at any point, you can
use ActivityManager.getMyMemoryState(RunningAppProcessInfo)
.
onTrimMemory
in interface ComponentCallbacks2
level
- The context of the trim, giving a hint of the amount of
trimming the application may like to perform. May be
ComponentCallbacks2.TRIM_MEMORY_COMPLETE
, ComponentCallbacks2.TRIM_MEMORY_MODERATE
,
ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
, ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
,
ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL
, ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW
,
or ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE
.public void onDestroyView()
onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.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(android.view.LayoutInflater, android.view.ViewGroup, android.os.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.public void onDestroy()
onStop()
and before onDetach()
.public void onDetach()
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()
.public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
setHasOptionsMenu(boolean)
. See
Activity.onCreateOptionsMenu
for more information.menu
- The options menu in which you place your items.setHasOptionsMenu(boolean)
,
onPrepareOptionsMenu(android.view.Menu)
,
onOptionsItemSelected(android.view.MenuItem)
public void onPrepareOptionsMenu(Menu menu)
Activity.onPrepareOptionsMenu
for more information.menu
- The options menu as last shown or first initialized by
onCreateOptionsMenu().setHasOptionsMenu(boolean)
,
onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater)
public void onDestroyOptionsMenu()
onCreateOptionsMenu(Menu, MenuInflater)
was not called).public boolean onOptionsItemSelected(MenuItem item)
Derived classes should call through to the base class for it to perform the default menu handling.
item
- The menu item that was selected.onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater)
public void onOptionsMenuClosed(Menu menu)
menu
- The options menu as last shown or first initialized by
onCreateOptionsMenu().public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
view
is about to be shown.
Unlike onCreateOptionsMenu(android.view.Menu, android.view.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.
onCreateContextMenu
in interface View.OnCreateContextMenuListener
menu
- The context menu that is being builtv
- The view for which the context menu is being builtmenuInfo
- Extra information about the item for which the
context menu should be shown. This information will vary
depending on the class of v.public void registerForContextMenu(View view)
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.view
- The view that should show a context menu.unregisterForContextMenu(View)
public void unregisterForContextMenu(View view)
View.OnCreateContextMenuListener
on the view.view
- The view that should stop showing a context menu.registerForContextMenu(View)
public boolean onContextItemSelected(MenuItem item)
Use MenuItem.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.
item
- The context menu item that was selected.public void setEnterSharedElementCallback(SharedElementCallback callback)
callback
- Used to manipulate the shared element transitions on this Fragment
when added not as a pop from the back stack.public void setEnterSharedElementTransitionCallback(SharedElementCallback callback)
public void setExitSharedElementCallback(SharedElementCallback callback)
callback
- Used to manipulate the shared element transitions on this Fragment
when added as a pop from the back stack.public void setExitSharedElementTransitionCallback(SharedElementCallback callback)
public void setEnterTransition(Transition transition)
ViewGroup.isTransitionGroup()
return true. Typical Transitions will extend
Visibility
as entering is governed by changing visibility from
View.INVISIBLE
to View.VISIBLE
. If transition
is null,
entering Views will remain unaffected.transition
- The Transition to use to move Views into the initial Scene.public Transition getEnterTransition()
ViewGroup.isTransitionGroup()
return true. Typical Transitions will extend
Visibility
as entering is governed by changing visibility from
View.INVISIBLE
to View.VISIBLE
.public void setReturnTransition(Transition transition)
ViewGroup.isTransitionGroup()
return true. Typical Transitions will extend
Visibility
as entering is governed by changing visibility from
View.VISIBLE
to View.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)
.transition
- The Transition to use to move Views out of the Scene when the Fragment
is preparing to close.public Transition getReturnTransition()
ViewGroup.isTransitionGroup()
return true. Typical Transitions will extend
Visibility
as entering is governed by changing visibility from
View.VISIBLE
to View.INVISIBLE
. If transition
is null,
entering Views will remain unaffected.public void setExitTransition(Transition transition)
ViewGroup.isTransitionGroup()
return true. Typical Transitions will extend
Visibility
as exiting is governed by changing visibility
from View.VISIBLE
to View.INVISIBLE
. If transition is null, the views will
remain unaffected.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.public Transition getExitTransition()
ViewGroup.isTransitionGroup()
return true. Typical Transitions will extend
Visibility
as exiting is governed by changing visibility
from View.VISIBLE
to View.INVISIBLE
. If transition is null, the views will
remain unaffected.public void setReenterTransition(Transition transition)
ViewGroup.isTransitionGroup()
return true. Typical Transitions
will extend Visibility
as exiting is governed by changing
visibility from View.VISIBLE
to View.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)
.transition
- The Transition to use to move Views into the scene when reentering from a
previously-started Activity.public Transition getReenterTransition()
ViewGroup.isTransitionGroup()
return true. Typical Transitions
will extend Visibility
as exiting is governed by changing
visibility from View.VISIBLE
to View.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 void setSharedElementEnterTransition(Transition transition)
ChangeBounds
. A null
value will cause transferred shared elements to blink to the final position.transition
- The Transition to use for shared elements transferred into the content
Scene.public Transition getSharedElementEnterTransition()
ChangeBounds
. A null
value will cause transferred shared elements to blink to the final position.public void setSharedElementReturnTransition(Transition transition)
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)
.transition
- The Transition to use for shared elements transferred out of the content
Scene.public Transition getSharedElementReturnTransition()
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 void setAllowEnterTransitionOverlap(boolean allow)
allow
- true to start the enter transition when possible or false to
wait until the exiting transition completes.public boolean getAllowEnterTransitionOverlap()
public void setAllowReturnTransitionOverlap(boolean allow)
allow
- true to start the reenter transition when possible or false to wait until the
return transition completes.public boolean getAllowReturnTransitionOverlap()
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args)
prefix
- Text to print at the front of each line.fd
- The raw file descriptor that the dump is being sent to.writer
- The PrintWriter to which you should dump your state. This will be
closed for you after you return.args
- additional arguments to the dump request.