FragmentManager
abstract class FragmentManager : FragmentResultOwner
Static library support version of the framework's android.app.FragmentManager. Used to write apps that run on platforms prior to Android 3.0. When running on Android 3.0 or above, this implementation is still used; it does not try to switch to the framework's implementation. See the framework FragmentManager documentation for a class overview.
Your activity must derive from FragmentActivity to use this. From such an activity, you can acquire the FragmentManager by calling getSupportFragmentManager.
Summary
Nested types |
|---|
interface FragmentManager.BackStackEntryRepresentation of an entry on the fragment back stack, as created with |
abstract class FragmentManager.FragmentLifecycleCallbacksCallback interface for listening to fragment state changes that happen within a given FragmentManager. |
|
Interface to watch for changes to the back stack. |
Constants |
|
|---|---|
const Int |
Flag for |
Public constructors |
|---|
Public functions |
|
|---|---|
Unit |
Add a |
Unit |
Add a new listener for changes to the fragment back stack. |
FragmentTransaction |
Start a series of edit operations on the Fragments associated with this FragmentManager. |
Unit |
clearBackStack(name: String)Clears the back stack previously saved via |
Unit |
clearFragmentResult(requestKey: String)Clears the stored result for the given requestKey. |
Unit |
clearFragmentResultListener(requestKey: String)Clears the stored |
Unit |
dump(Print the FragmentManager's state into the given stream. |
java-static Unit |
This function is deprecated. FragmentManager now respects |
java-static Unit |
@PredictiveBackControlControl whether FragmentManager uses the new state predictive back feature that allows seeing the previous Fragment when using gesture back. |
Boolean |
After a |
java-static F |
<F : Fragment?> findFragment(view: View) |
Fragment? |
findFragmentById(id: @IdRes Int)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. |
Fragment? |
findFragmentByTag(tag: String?)Finds a fragment that was identified by the given tag either when inflated from XML or as supplied when added in a transaction. |
java-static FragmentManager |
findFragmentManager(view: View)Recurse up the view hierarchy, looking for a FragmentManager |
FragmentManager.BackStackEntry |
getBackStackEntryAt(index: Int)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. |
Fragment? |
getFragment(bundle: Bundle, key: String)Retrieve the current Fragment instance for a reference previously placed with |
FragmentFactory |
Gets the current |
(Mutable)List<Fragment!> |
Get a list of all fragments that are currently added to the FragmentManager. |
Fragment? |
Return the currently active primary navigation fragment for this FragmentManager. |
FragmentStrictMode.Policy? |
Returns the current policy for this FragmentManager. |
Boolean |
Returns true if the final |
Boolean |
Returns |
Unit |
onContainerAvailable(container: FragmentContainerView)Callback for when the |
Unit |
Pop the top state off the back stack. |
Unit |
popBackStack(id: Int, flags: Int)Pop all back stack states up to the one with the given identifier. |
Unit |
popBackStack(name: String?, flags: Int)Pop the last fragment transition from the manager's fragment back stack. |
Boolean |
Like |
Boolean |
popBackStackImmediate(id: Int, flags: Int)Like |
Boolean |
@MainThreadLike |
Unit |
putFragment(bundle: Bundle, key: String, fragment: Fragment)Put a reference to a fragment in a Bundle. |
Unit |
registerFragmentLifecycleCallbacks(Registers a |
Unit |
Remove a |
Unit |
Remove a listener that was previously added with |
Unit |
restoreBackStack(name: String)Restores the back stack previously saved via |
Unit |
saveBackStack(name: String)Save the back stack. |
Fragment.SavedState? |
saveFragmentInstanceState(fragment: Fragment)Save the current instance state of the given Fragment. |
Unit |
setFragmentFactory(fragmentFactory: FragmentFactory)Set a |
Unit |
setFragmentResult(requestKey: String, result: Bundle)Sets the given result for the requestKey. |
Unit |
setFragmentResultListener(Sets the |
Unit |
setStrictModePolicy(policy: FragmentStrictMode.Policy?)Sets the policy for what actions should be detected, as well as the penalty if such actions occur. |
String |
toString() |
Unit |
Unregisters a previously registered |
Extension functions |
|
|---|---|
inline Unit |
FragmentManager.commit(allowStateLoss: Boolean, body: FragmentTransaction.() -> Unit)Run |
inline Unit |
@MainThreadRun |
inline Unit |
FragmentManager.This function is deprecated. Use commit { .. } or commitNow { .. } extensions |
Constants
POP_BACK_STACK_INCLUSIVE
const val POP_BACK_STACK_INCLUSIVE = 1: Int
Flag for popBackStack and popBackStack: 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.
Public constructors
Public functions
addFragmentOnAttachListener
fun addFragmentOnAttachListener(listener: FragmentOnAttachListener): Unit
Add a FragmentOnAttachListener that should receive a call to onAttachFragment when a new Fragment is attached to this FragmentManager.
| Parameters | |
|---|---|
listener: FragmentOnAttachListener |
Listener to add |
addOnBackStackChangedListener
fun addOnBackStackChangedListener(
listener: FragmentManager.OnBackStackChangedListener
): Unit
Add a new listener for changes to the fragment back stack.
beginTransaction
fun beginTransaction(): FragmentTransaction
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 FragmentActivity.onSaveInstanceState() (and prior to a following FragmentActivity.onStart or FragmentActivity.onResume(), 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.
clearBackStack
fun clearBackStack(name: String): Unit
Clears the back stack previously saved via saveBackStack. This will result in all of the transactions that made up that back stack to be thrown away, thus destroying any fragments that were added through those transactions. All state of those fragments will be cleared as part of this process. If no state was previously saved with the given name, this operation does nothing.
This function is asynchronous -- it enqueues the request to clear, but the action will not be performed until the application returns to its event loop.
| Parameters | |
|---|---|
name: String |
The name of the back stack previously saved by |
clearFragmentResult
fun clearFragmentResult(requestKey: String): Unit
Clears the stored result for the given requestKey. This clears any result that was previously set via setFragmentResult that hasn't yet been delivered to a FragmentResultListener.
| Parameters | |
|---|---|
requestKey: String |
key used to identify the result |
clearFragmentResultListener
fun clearFragmentResultListener(requestKey: String): Unit
Clears the stored FragmentResultListener for the given requestKey. This clears any FragmentResultListener that was previously set via setFragmentResultListener.
| Parameters | |
|---|---|
requestKey: String |
key used to identify the result |
dump
fun dump(
prefix: String,
fd: FileDescriptor?,
writer: PrintWriter,
args: Array<String!>?
): Unit
Print the FragmentManager'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 |
A PrintWriter to which the dump is to be set. |
args: Array<String!>? |
Additional arguments to the dump request. |
java-static funenableDebugLogging(enabled: Boolean): Unit
Control whether the framework's internal fragment manager debugging logs are turned on. If enabled, you will see output in logcat as the framework performs fragment operations.
| See also | |
|---|---|
isLoggable |
enablePredictiveBack
@PredictiveBackControl
java-static fun enablePredictiveBack(enabled: Boolean): Unit
Control whether FragmentManager uses the new state predictive back feature that allows seeing the previous Fragment when using gesture back.
This should only be changed before any fragment transactions are done (i.e., in your Application class or prior to super.onCreate() in every activity).
| Parameters | |
|---|---|
enabled: Boolean |
Whether predictive back should be enabled. |
executePendingTransactions
@MainThread
fun executePendingTransactions(): Boolean
After a FragmentTransaction is committed with FragmentTransaction.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 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 postponeEnterTransition has been called.
| Returns | |
|---|---|
Boolean |
Returns true if there were any pending transactions to be executed. |
findFragment
java-static fun <F : Fragment?> findFragment(view: View): F
Find a Fragment associated with the given View. This method will locate the Fragment associated with this view. This is automatically populated for the View returned by onCreateView and its children.
| Parameters | |
|---|---|
view: View |
the view to search from |
| Returns | |
|---|---|
F |
the locally scoped |
| Throws | |
|---|---|
java.lang.IllegalStateException |
if the given view does not correspond with a |
findFragmentById
fun findFragmentById(id: @IdRes Int): Fragment?
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 | |
|---|---|
Fragment? |
The fragment if found or null otherwise. |
findFragmentByTag
fun findFragmentByTag(tag: String?): Fragment?
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: String? |
the tag used to search for the fragment |
| Returns | |
|---|---|
Fragment? |
The fragment if found or null otherwise. |
findFragmentManager
java-static fun findFragmentManager(view: View): FragmentManager
Recurse up the view hierarchy, looking for a FragmentManager
| Parameters | |
|---|---|
view: View |
the view to search from |
| Returns | |
|---|---|
FragmentManager |
The containing |
| Throws | |
|---|---|
java.lang.IllegalStateException |
if there no Fragment associated with the view and the view's context is not a |
getBackStackEntryAt
fun getBackStackEntryAt(index: Int): FragmentManager.BackStackEntry
Return the BackStackEntry at index index in the back stack; entries start index 0 being the bottom of the stack.
getBackStackEntryCount
fun getBackStackEntryCount(): Int
Return the number of entries currently in the back stack.
getFragment
fun getFragment(bundle: Bundle, key: String): Fragment?
Retrieve the current Fragment instance for a reference previously placed with putFragment.
| Parameters | |
|---|---|
bundle: Bundle |
The bundle from which to retrieve the fragment reference. |
key: String |
The name of the entry in the bundle. |
| Returns | |
|---|---|
Fragment? |
Returns the current Fragment instance that is associated with the given reference. |
getFragmentFactory
fun getFragmentFactory(): FragmentFactory
Gets the current FragmentFactory used to instantiate new Fragment instances.
If no factory has been explicitly set on this FragmentManager via setFragmentFactory, the FragmentFactory of the parent FragmentManager will be returned.
| Returns | |
|---|---|
FragmentFactory |
the current FragmentFactory |
getFragments
fun getFragments(): (Mutable)List<Fragment!>
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.
getPrimaryNavigationFragment
fun getPrimaryNavigationFragment(): Fragment?
Return the currently active primary navigation fragment for this FragmentManager. The primary navigation fragment is set by fragment transactions using setPrimaryNavigationFragment.
The primary navigation fragment's child FragmentManager will be called first to process delegated navigation actions such as popBackStack if no ID or transaction name is provided to pop to.
| Returns | |
|---|---|
Fragment? |
the fragment designated as the primary navigation fragment |
getStrictModePolicy
fun getStrictModePolicy(): FragmentStrictMode.Policy?
Returns the current policy for this FragmentManager. If no policy is set, returns null.
isDestroyed
fun isDestroyed(): Boolean
Returns true if the final Activity.onDestroy() call has been made on the FragmentManager's Activity, so this instance is now dead.
isStateSaved
fun isStateSaved(): Boolean
Returns true 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 as popBackStackImmediate or any FragmentTransaction using commit instead of commitAllowingStateLoss will change the state and will result in an error.
| Returns | |
|---|---|
Boolean |
true if this FragmentManager's state has already been saved by its host |
onContainerAvailable
fun onContainerAvailable(container: FragmentContainerView): Unit
Callback for when the FragmentContainerView becomes available in the view hierarchy and the fragment manager can add the fragment view to its hierarchy.
| Parameters | |
|---|---|
container: FragmentContainerView |
the container that the active fragment should add their views to |
popBackStack
fun popBackStack(): Unit
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.
popBackStack
fun popBackStack(id: Int, flags: Int): Unit
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: Int |
Identifier of the stated to be popped. If no identifier exists, false is returned. The identifier is the number returned by |
flags: Int |
Either 0 or |
popBackStack
fun popBackStack(name: String?, flags: Int): Unit
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: String? |
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. The |
flags: Int |
Either 0 or |
popBackStackImmediate
@MainThread
fun popBackStackImmediate(): Boolean
Like popBackStack, but performs the operation immediately inside of the call. This is like calling executePendingTransactions afterwards without forcing the start of postponed Transactions.
| Returns | |
|---|---|
Boolean |
Returns true if there was something popped, else false. |
popBackStackImmediate
fun popBackStackImmediate(id: Int, flags: Int): Boolean
Like popBackStack, but performs the operation immediately inside of the call. This is like calling executePendingTransactions afterwards without forcing the start of postponed Transactions.
| Returns | |
|---|---|
Boolean |
Returns true if there was something popped, else false. |
popBackStackImmediate
@MainThread
fun popBackStackImmediate(name: String?, flags: Int): Boolean
Like popBackStack, but performs the operation immediately inside of the call. This is like calling executePendingTransactions afterwards without forcing the start of postponed Transactions.
| Returns | |
|---|---|
Boolean |
Returns true if there was something popped, else false. |
putFragment
fun putFragment(bundle: Bundle, key: String, fragment: Fragment): Unit
Put a reference to a fragment in a Bundle. This Bundle can be persisted as saved state, and when later restoring getFragment will return the current instance of the same fragment.
registerFragmentLifecycleCallbacks
fun registerFragmentLifecycleCallbacks(
cb: FragmentManager.FragmentLifecycleCallbacks,
recursive: Boolean
): Unit
Registers a FragmentLifecycleCallbacks to listen to fragment lifecycle events happening in this FragmentManager. All registered callbacks will be automatically unregistered when this FragmentManager is destroyed.
| Parameters | |
|---|---|
cb: FragmentManager.FragmentLifecycleCallbacks |
Callbacks to register |
recursive: Boolean |
true to automatically register this callback for all child FragmentManagers |
removeFragmentOnAttachListener
fun removeFragmentOnAttachListener(listener: FragmentOnAttachListener): Unit
Remove a FragmentOnAttachListener that was previously added via addFragmentOnAttachListener. It will no longer get called when a new Fragment is attached.
| Parameters | |
|---|---|
listener: FragmentOnAttachListener |
Listener to remove |
removeOnBackStackChangedListener
fun removeOnBackStackChangedListener(
listener: FragmentManager.OnBackStackChangedListener
): Unit
Remove a listener that was previously added with addOnBackStackChangedListener.
restoreBackStack
fun restoreBackStack(name: String): Unit
Restores the back stack previously saved via saveBackStack. This will result in all of the transactions that made up that back stack to be re-executed, thus re-adding any fragments that were added through those transactions. All state of those fragments will be restored as part of this process. If no state was previously saved with the given name, this operation does nothing.
This function is asynchronous -- it enqueues the request to restore, but the action will not be performed until the application returns to its event loop.
| Parameters | |
|---|---|
name: String |
The name of the back stack previously saved by |
saveBackStack
fun saveBackStack(name: String): Unit
Save the back stack. While this functions similarly to popBackStack, it does not throw away the state of any fragments that were added through those transactions. Instead, the back stack that is saved by this method can later be restored with its state in tact.
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: String |
The name set by |
saveFragmentInstanceState
fun saveFragmentInstanceState(fragment: Fragment): Fragment.SavedState?
Save the current instance state of the given Fragment. This can be used later when creating a new instance of the Fragment and adding it to the fragment manager, to have it create itself to match the current state returned here. Note that there are limits on how this can be used:
- The Fragment must currently be attached to the FragmentManager.
- A new Fragment created using this saved state must be the same class type as the Fragment it was created from.
- The saved state can not contain dependencies on other fragments -- that is it can't use
putFragmentto store a fragment reference because that reference may not be valid when this saved state is later used. Likewise the Fragment's target and result code are not included in this state.
| Parameters | |
|---|---|
fragment: Fragment |
The Fragment whose state is to be saved. |
| Returns | |
|---|---|
Fragment.SavedState? |
The generated state. This will be null if there was no interesting state created by the fragment. |
setFragmentFactory
fun setFragmentFactory(fragmentFactory: FragmentFactory): Unit
Set a FragmentFactory 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: FragmentFactory |
the factory to use to create new Fragment instances |
| See also | |
|---|---|
getFragmentFactory |
setFragmentResult
fun setFragmentResult(requestKey: String, result: Bundle): Unit
Sets the given result for the requestKey. This result will be delivered to a FragmentResultListener that is called given to setFragmentResultListener with the same requestKey. If no FragmentResultListener with the same key is set or the Lifecycle associated with the listener is not at least STARTED, the result is stored until one becomes available, or clearFragmentResult is called with the same requestKey.
setFragmentResultListener
fun setFragmentResultListener(
requestKey: String,
lifecycleOwner: LifecycleOwner,
listener: FragmentResultListener
): Unit
Sets the FragmentResultListener for a given requestKey. Once the given LifecycleOwner is at least in the STARTED state, any results set by setFragmentResult using the same requestKey will be delivered to the callback. The callback will remain active until the LifecycleOwner reaches the DESTROYED state or clearFragmentResultListener is called with the same requestKey.
| Parameters | |
|---|---|
requestKey: String |
requestKey used to identify the result |
lifecycleOwner: LifecycleOwner |
lifecycleOwner for handling the result |
listener: FragmentResultListener |
listener for result changes |
setStrictModePolicy
fun setStrictModePolicy(policy: FragmentStrictMode.Policy?): Unit
Sets the policy for what actions should be detected, as well as the penalty if such actions occur. The child FragmentManager of all Fragments in this FragmentManager will also use this policy if one is not explicitly set. Pass null to clear the policy.
| Parameters | |
|---|---|
policy: FragmentStrictMode.Policy? |
the policy to put into place |
unregisterFragmentLifecycleCallbacks
fun unregisterFragmentLifecycleCallbacks(
cb: FragmentManager.FragmentLifecycleCallbacks
): Unit
Unregisters a previously registered FragmentLifecycleCallbacks. 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: FragmentManager.FragmentLifecycleCallbacks |
Callbacks to unregister |
Extension functions
commit
inline fun FragmentManager.commit(allowStateLoss: Boolean = false, body: FragmentTransaction.() -> Unit): Unit
Run body in a FragmentTransaction which is automatically committed if it completes without exception.
The transaction will be completed by calling FragmentTransaction.commit unless allowStateLoss is set to true in which case FragmentTransaction.commitAllowingStateLoss will be used.
commitNow
@MainThread
inline fun FragmentManager.commitNow(allowStateLoss: Boolean = false, body: FragmentTransaction.() -> Unit): Unit
Run body in a FragmentTransaction which is automatically committed if it completes without exception.
The transaction will be completed by calling FragmentTransaction.commitNow unless allowStateLoss is set to true in which case FragmentTransaction.commitNowAllowingStateLoss will be used.
transaction
inline fun FragmentManager.transaction(
now: Boolean = false,
allowStateLoss: Boolean = false,
body: FragmentTransaction.() -> Unit
): Unit
Run body in a FragmentTransaction which is automatically committed if it completes without exception.
One of four commit functions will be used based on the values of now and allowStateLoss:
| now | allowStateLoss | Method | | ----- | ---------------- | ------------------------------ | | false | false | commit() | | false | true | commitAllowingStateLoss() | | true | false | commitNow() | | true | true | commitNowAllowingStateLoss() |