Class FragmentManager
- All Implemented Interfaces:
FragmentResultOwner
Fragment
objects inside a host.
You should never instantiate a FragmentManager directly, but instead
operate via the APIs on Fragment
, or FragmentController
to
retrieve an instance.
For more information about using fragments, read the Android Fragments developer guide.
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic interface
Representation of an entry on the fragment back stack, as created withFragmentTransaction.addToBackStack()
.static interface
Interface to watch for changes to the back stack. -
Field Summary
Modifier and TypeFieldDescriptionstatic final int
Flag forpopBackStack(String, int)
andpopBackStack(int, int)
: If set, and the name or ID of a back stack entry has been supplied, then all matching entries will be consumed until one that doesn't match is found or the bottom of the stack is reached. -
Method Summary
Modifier and TypeMethodDescriptionvoid
Add aFragmentOnAttachListener
that should receive a call toFragmentOnAttachListener.onAttachFragment(FragmentManager, Fragment)
when a new Fragment is attached to this FragmentManager.void
Add a new listener for changes to the fragment back stack.Start a series of edit operations on the Fragments associated with this FragmentManager.void
clearFragmentResult
(String requestKey) Clears the stored result for the given requestKey.void
clearFragmentResultListener
(String requestKey) Clears the storedFragmentResultListener
for the given requestKey.void
dump
(String prefix, FileDescriptor fd, PrintWriter writer, String... args) Print the FragmentManager's state into the given stream.boolean
After aFragmentTransaction
is committed withFragmentTransaction.commit()
, it is scheduled to be executed asynchronously on the process's main thread.static <F extends Fragment>
FfindFragment
(View view) findFragmentById
(int id) Finds a fragment that was identified by the given id either when inflated from XML or as the container ID when added in a transaction.findFragmentByTag
(String tag) Finds a fragment that was identified by the given tag either when inflated from XML or as supplied when added in a transaction.getBackStackEntryAt
(int index) Return the BackStackEntry at index index in the back stack; entries start index 0 being the bottom of the stack.int
Return the number of entries currently in the back stack.getFragment
(DataSet bundle, String key) Retrieve the current Fragment instance for a reference previously placed withputFragment(DataSet, String, Fragment)
.Gets the currentFragmentFactory
used to instantiate new Fragment instances.Get a list of all fragments that are currently added to the FragmentManager.Return the currently active primary navigation fragment for this FragmentManager.boolean
Returns true if the finalonDestroy()
call has been made on the FragmentManager's Activity, so this instance is now dead.boolean
Returnstrue
if the FragmentManager's state has already been saved by its host.void
Pop the top state off the back stack.void
popBackStack
(int id, int flags) Pop all back stack states up to the one with the given identifier.void
popBackStack
(String name, int flags) Pop the last fragment transition from the manager's fragment back stack.boolean
LikepopBackStack()
, but performs the operation immediately inside the call.boolean
popBackStackImmediate
(int id, int flags) LikepopBackStack(int, int)
, but performs the operation immediately inside the call.boolean
popBackStackImmediate
(String name, int flags) LikepopBackStack(String, int)
, but performs the operation immediately inside the call.void
putFragment
(DataSet bundle, String key, Fragment fragment) Put a reference to a fragment in a DataSet.void
registerFragmentLifecycleCallbacks
(FragmentLifecycleCallbacks cb, boolean recursive) Registers aFragmentLifecycleCallbacks
to listen to fragment lifecycle events happening in this FragmentManager.void
Remove aFragmentOnAttachListener
that was previously added viaaddFragmentOnAttachListener(FragmentOnAttachListener)
.void
Remove a listener that was previously added withaddOnBackStackChangedListener(OnBackStackChangedListener)
.void
setFragmentFactory
(FragmentFactory fragmentFactory) Set aFragmentFactory
for this FragmentManager that will be used to create new Fragment instances from this point onward.void
setFragmentResult
(String requestKey, DataSet result) Sets the given result for the requestKey.void
setFragmentResultListener
(String requestKey, LifecycleOwner lifecycleOwner, FragmentResultListener listener) Sets theFragmentResultListener
for a given requestKey.toString()
void
Unregisters a previously registeredFragmentLifecycleCallbacks
.
-
Field Details
-
POP_BACK_STACK_INCLUSIVE
public static final int POP_BACK_STACK_INCLUSIVEFlag forpopBackStack(String, int)
andpopBackStack(int, int)
: If set, and the name or ID of a back stack entry has been supplied, then all matching entries will be consumed until one that doesn't match is found or the bottom of the stack is reached. Otherwise, all entries up to but not including that entry will be removed.- See Also:
-
-
Method Details
-
beginTransaction
Start a series of edit operations on the Fragments associated with this FragmentManager.Note: A fragment transaction can only be created/committed prior to an activity saving its state. If you try to commit a transaction after
onSaveInstanceState()
and prior to a followingonStart
oronResume()
, you will get an error. This is because the framework takes care of saving your current fragments in the state, and if changes are made after the state is saved then they will be lost. -
executePendingTransactions
public boolean executePendingTransactions()After aFragmentTransaction
is committed withFragmentTransaction.commit()
, it is scheduled to be executed asynchronously on the process's main thread. If you want to immediately executing any such pending operations, you can call this function (only from the main thread) to do so. Note that all callbacks and other related behavior will be done from within this call, so be careful about where this is called from.If you are committing a single transaction that does not modify the fragment back stack, strongly consider using
FragmentTransaction.commitNow()
instead. This can help avoid unwanted side effects when other code in your app has pending committed transactions that expect different timing.This also forces the start of any postponed Transactions where
Fragment.postponeEnterTransition()
has been called.- Returns:
- Returns true if there were any pending transactions to be executed.
-
popBackStack
public void popBackStack()Pop the top state off the back stack. This function is asynchronous -- it enqueues the request to pop, but the action will not be performed until the application returns to its event loop. -
popBackStackImmediate
public boolean popBackStackImmediate()LikepopBackStack()
, but performs the operation immediately inside the call. This is like callingexecutePendingTransactions()
afterwards without forcing the start of postponed Transactions.- Returns:
- Returns true if there was something popped, else false.
-
popBackStack
Pop the last fragment transition from the manager's fragment back stack. This function is asynchronous -- it enqueues the request to pop, but the action will not be performed until the application returns to its event loop.- Parameters:
name
- If non-null, this is the name of a previous back state to look for; if found, all states up to that state will be popped. ThePOP_BACK_STACK_INCLUSIVE
flag can be used to control whether the named state itself is popped. If null, only the top state is popped.flags
- Either 0 orPOP_BACK_STACK_INCLUSIVE
.
-
popBackStackImmediate
LikepopBackStack(String, int)
, but performs the operation immediately inside the call. This is like callingexecutePendingTransactions()
afterwards without forcing the start of postponed Transactions.- Returns:
- Returns true if there was something popped, else false.
-
popBackStack
public void popBackStack(int id, int flags) Pop all back stack states up to the one with the given identifier. This function is asynchronous -- it enqueues the request to pop, but the action will not be performed until the application returns to its event loop.- Parameters:
id
- Identifier of the stated to be popped. If no identifier exists, false is returned. The identifier is the number returned byFragmentTransaction.commit()
. ThePOP_BACK_STACK_INCLUSIVE
flag can be used to control whether the named state itself is popped.flags
- Either 0 orPOP_BACK_STACK_INCLUSIVE
.
-
popBackStackImmediate
public boolean popBackStackImmediate(int id, int flags) LikepopBackStack(int, int)
, but performs the operation immediately inside the call. This is like callingexecutePendingTransactions()
afterwards without forcing the start of postponed Transactions.- Returns:
- Returns true if there was something popped, else false.
-
getBackStackEntryCount
public int getBackStackEntryCount()Return the number of entries currently in the back stack. -
getBackStackEntryAt
Return the BackStackEntry at index index in the back stack; entries start index 0 being the bottom of the stack. -
addOnBackStackChangedListener
public void addOnBackStackChangedListener(@Nonnull FragmentManager.OnBackStackChangedListener listener) Add a new listener for changes to the fragment back stack. -
removeOnBackStackChangedListener
public void removeOnBackStackChangedListener(@Nonnull FragmentManager.OnBackStackChangedListener listener) Remove a listener that was previously added withaddOnBackStackChangedListener(OnBackStackChangedListener)
. -
setFragmentResult
Description copied from interface:FragmentResultOwner
Sets the given result for the requestKey. This result will be delivered to aFragmentResultListener
that is called given toFragmentResultOwner.setFragmentResultListener(String, LifecycleOwner, FragmentResultListener)
with the same requestKey. If noFragmentResultListener
with the same key is set or the Lifecycle associated with the listener is not at leastLifecycle.State.STARTED
, the result is stored until one becomes available, orFragmentResultOwner.clearFragmentResult(String)
is called with the same requestKey.- Specified by:
setFragmentResult
in interfaceFragmentResultOwner
- Parameters:
requestKey
- key used to identify the resultresult
- the result to be passed to another fragment
-
clearFragmentResult
Description copied from interface:FragmentResultOwner
Clears the stored result for the given requestKey.This clears any result that was previously set via
FragmentResultOwner.setFragmentResult(String, DataSet)
that hasn't yet been delivered to aFragmentResultListener
.- Specified by:
clearFragmentResult
in interfaceFragmentResultOwner
- Parameters:
requestKey
- key used to identify the result
-
setFragmentResultListener
public void setFragmentResultListener(@Nonnull String requestKey, @Nonnull LifecycleOwner lifecycleOwner, @Nonnull FragmentResultListener listener) Description copied from interface:FragmentResultOwner
Sets theFragmentResultListener
for a given requestKey. Once the givenLifecycleOwner
is at least in theLifecycle.State.STARTED
state, any results set byFragmentResultOwner.setFragmentResult(String, DataSet)
using the same requestKey will be delivered to thecallback
. The callback will remain active until the LifecycleOwner reaches theLifecycle.State.DESTROYED
state orFragmentResultOwner.clearFragmentResultListener(String)
is called with the same requestKey.- Specified by:
setFragmentResultListener
in interfaceFragmentResultOwner
- Parameters:
requestKey
- requestKey used to identify the resultlifecycleOwner
- lifecycleOwner for handling the resultlistener
- listener for result changes
-
clearFragmentResultListener
Description copied from interface:FragmentResultOwner
Clears the storedFragmentResultListener
for the given requestKey.This clears any
FragmentResultListener
that was previously set viaFragmentResultOwner.setFragmentResultListener(String, LifecycleOwner, FragmentResultListener)
.- Specified by:
clearFragmentResultListener
in interfaceFragmentResultOwner
- Parameters:
requestKey
- key used to identify the result
-
putFragment
Put a reference to a fragment in a DataSet. This DataSet can be persisted as saved state, and when later restoringgetFragment(DataSet, String)
will return the current instance of the same fragment.- Parameters:
bundle
- The bundle in which to put the fragment reference.key
- The name of the entry in the bundle.fragment
- The Fragment whose reference is to be stored.
-
getFragment
Retrieve the current Fragment instance for a reference previously placed withputFragment(DataSet, String, Fragment)
.- Parameters:
bundle
- The bundle from which to retrieve the fragment reference.key
- The name of the entry in the bundle.- Returns:
- Returns the current Fragment instance that is associated with the given reference.
-
findFragment
Find aFragment
associated with the givenView
.This method will locate the
Fragment
associated with this view. This is automatically populated for the View returned byFragment.onCreateView(icyllis.modernui.view.LayoutInflater, icyllis.modernui.view.ViewGroup, icyllis.modernui.util.DataSet)
and its children.- Type Parameters:
F
- the fragment type- Parameters:
view
- the view to search from- Returns:
- the locally scoped
Fragment
to the given view - Throws:
IllegalStateException
- if the given view does not correspond with aFragment
.ClassCastException
- if the given type parameter is wrong
-
getFragments
Get a list of all fragments that are currently added to the FragmentManager. This may include those that are hidden as well as those that are shown. This will not include any fragments only in the back stack, or fragments that are detached or removed.The order of the fragments in the list is the order in which they were added or attached.
- Returns:
- A list of all fragments that are added to the FragmentManager.
-
isDestroyed
public boolean isDestroyed()Returns true if the finalonDestroy()
call has been made on the FragmentManager's Activity, so this instance is now dead. -
toString
-
dump
public void dump(@Nonnull String prefix, @Nullable FileDescriptor fd, @Nonnull PrintWriter writer, @Nullable String... args) Print the FragmentManager's state into the given stream.- Parameters:
prefix
- Text to print at the front of each line.fd
- The raw file descriptor that the dump is being sent to.writer
- A PrintWriter to which the dump is to be set.args
- Additional arguments to the dump request.
-
findFragmentById
Finds a fragment that was identified by the given id either when inflated from XML or as the container ID when added in a transaction. This first searches through fragments that are currently added to the manager's activity; if no such fragment is found, then all fragments currently on the back stack associated with this ID are searched.- Returns:
- The fragment if found or null otherwise.
-
findFragmentByTag
Finds a fragment that was identified by the given tag either when inflated from XML or as supplied when added in a transaction. This first searches through fragments that are currently added to the manager's activity; if no such fragment is found, then all fragments currently on the back stack are searched.If provided a
null
tag, this method returns null.- Parameters:
tag
- the tag used to search for the fragment- Returns:
- The fragment if found or null otherwise.
-
isStateSaved
public boolean isStateSaved()Returnstrue
if the FragmentManager's state has already been saved by its host. Any operations that would change saved state should not be performed if this method returns true. For example, any popBackStack() method, such aspopBackStackImmediate()
or any FragmentTransaction usingFragmentTransaction.commit()
instead ofFragmentTransaction.commitAllowingStateLoss()
will change the state and will result in an error.- Returns:
- true if this FragmentManager's state has already been saved by its host
-
setFragmentFactory
Set aFragmentFactory
for this FragmentManager that will be used to create new Fragment instances from this point onward.The
child FragmentManager
of all Fragments in this FragmentManager will also use this factory if one is not explicitly set.- Parameters:
fragmentFactory
- the factory to use to create new Fragment instances- See Also:
-
getFragmentFactory
Gets the currentFragmentFactory
used to instantiate new Fragment instances.If no factory has been explicitly set on this FragmentManager via
setFragmentFactory(FragmentFactory)
, the FragmentFactory of theparent FragmentManager
will be returned.- Returns:
- the current FragmentFactory
-
registerFragmentLifecycleCallbacks
public void registerFragmentLifecycleCallbacks(@Nonnull FragmentLifecycleCallbacks cb, boolean recursive) Registers aFragmentLifecycleCallbacks
to listen to fragment lifecycle events happening in this FragmentManager. All registered callbacks will be automatically unregistered when this FragmentManager is destroyed.- Parameters:
cb
- Callbacks to registerrecursive
- true to automatically register this callback for all child FragmentManagers
-
unregisterFragmentLifecycleCallbacks
Unregisters a previously registeredFragmentLifecycleCallbacks
. If the callback was not previously registered this call has no effect. All registered callbacks will be automatically unregistered when this FragmentManager is destroyed.- Parameters:
cb
- Callbacks to unregister
-
addFragmentOnAttachListener
Add aFragmentOnAttachListener
that should receive a call toFragmentOnAttachListener.onAttachFragment(FragmentManager, Fragment)
when a new Fragment is attached to this FragmentManager.- Parameters:
listener
- Listener to add
-
removeFragmentOnAttachListener
Remove aFragmentOnAttachListener
that was previously added viaaddFragmentOnAttachListener(FragmentOnAttachListener)
. It will no longer get called when a new Fragment is attached.- Parameters:
listener
- Listener to remove
-