欢迎参加我们将于 6 月 3 日举行的 #Android11:Beta 版发布会

androidx.fragment.app

Classes

DialogFragment

Static library support version of the framework's android.app.DialogFragment.

Fragment

Static library support version of the framework's android.app.Fragment.

FragmentActivity

Base class for activities that want to use the support-based Fragments.

FragmentContainer

Callbacks to a Fragment's container.

FragmentContainerView

FragmentContainerView is a customized Layout designed specifically for Fragments.

FragmentController

Provides integration points with a FragmentManager for a fragment host.

FragmentFactory

Interface used to control the instantiation of Fragment instances.

FragmentHostCallback

Integration points with the Fragment host.

FragmentManager

Static library support version of the framework's android.app.FragmentManager.

FragmentManagerNonConfig

FragmentManagerNonConfig stores the retained instance fragments across activity recreation events.

FragmentPagerAdapter

Implementation of PagerAdapter that represents each page as a Fragment that is persistently kept in the fragment manager as long as the user can return to the page.

FragmentStatePagerAdapter

Implementation of PagerAdapter that uses a Fragment to manage each page.

FragmentTabHost

Special TabHost that allows the use of Fragment objects for its tab content.

FragmentTransaction

Static library support version of the framework's android.app.FragmentTransaction.

ListFragment

Static library support version of the framework's android.app.ListFragment.

Extension functions summary

For android.view.View
F

Find a Fragment associated with a View.

For Fragment
Lazy<VM>
Fragment.activityViewModels(noinline factoryProducer: () -> ViewModelProvider.Factory = null)

Returns a property delegate to access parent activity's ViewModel, if factoryProducer is specified then ViewModelProvider.Factory returned by it will be used to create ViewModel first time.

Unit

Clears the stored result for the given requestKey.

Unit

Clears the stored FragmentResultListener for the given requestKey.

Lazy<VM>
Fragment.createViewModelLazy(viewModelClass: KClass<VM>, storeProducer: () -> ViewModelStore, factoryProducer: () -> ViewModelProvider.Factory = null)

Helper method for creation of ViewModelLazy, that resolves null passed as factoryProducer to default factory.

Unit
Fragment.setFragmentResult(requestKey: String, result: Bundle)

Sets the given result for the requestKey.

Unit
Fragment.setFragmentResultListener(requestKey: String, crossinline listener: (resultKey: String, bundle: Bundle) -> Unit)

Sets the FragmentResultListener for a given requestKey.

Lazy<VM>
Fragment.viewModels(noinline ownerProducer: () -> ViewModelStoreOwner = { this }, noinline factoryProducer: () -> ViewModelProvider.Factory = null)

Returns a property delegate to access ViewModel by default scoped to this Fragment:

For FragmentTransaction
FragmentTransaction
FragmentTransaction.add(@IdRes containerViewId: Int, tag: String? = null, args: Bundle? = null)

Add a fragment to the associated FragmentManager, inflating the Fragment's view into the container view specified by containerViewId, to later retrieve via FragmentManager.findFragmentById.

FragmentTransaction
FragmentTransaction.add(tag: String, args: Bundle? = null)

Add a fragment to the associated FragmentManager without adding the Fragment to any container view.

FragmentTransaction
FragmentTransaction.replace(@IdRes containerViewId: Int, tag: String? = null, args: Bundle? = null)

Replace an existing fragment that was added to a container.

For FragmentManager
Unit
FragmentManager.commit(allowStateLoss: Boolean = false, body: FragmentTransaction.() -> Unit)

Run body in a FragmentTransaction which is automatically committed if it completes without exception.

Unit
FragmentManager.commitNow(allowStateLoss: Boolean = false, body: FragmentTransaction.() -> Unit)

Run body in a FragmentTransaction which is automatically committed if it completes without exception.

Unit
FragmentManager.transaction(now: Boolean = false, allowStateLoss: Boolean = false, body: FragmentTransaction.() -> Unit)

Run body in a FragmentTransaction which is automatically committed if it completes without exception.

For FragmentResultOwner
Unit
FragmentResultOwner.setFragmentResultListener(requestKey: String, lifecycleOwner: LifecycleOwner, crossinline listener: (resultKey: String, bundle: Bundle) -> Unit)

Sets the FragmentResultListener for a given requestKey.

Extension functions

activityViewModels

@MainThread inline fun <reified VM : ViewModel> Fragment.activityViewModels(noinline factoryProducer: () -> ViewModelProvider.Factory = null): Lazy<VM>

Returns a property delegate to access parent activity's ViewModel, if factoryProducer is specified then ViewModelProvider.Factory returned by it will be used to create ViewModel first time. Otherwise, the activity's androidx.activity.ComponentActivity.getDefaultViewModelProviderFactory will be used.

class MyFragment : Fragment() {
    val viewmodel: MyViewModel by activityViewModels()
}

This property can be accessed only after this Fragment is attached i.e., after Fragment.onAttach, and access prior to that will result in IllegalArgumentException.

add

inline fun <reified F : Fragment> FragmentTransaction.add(
    @IdRes containerViewId: Int,
    tag: String? = null,
    args: Bundle? = null
): FragmentTransaction

Add a fragment to the associated FragmentManager, inflating the Fragment's view into the container view specified by containerViewId, to later retrieve via FragmentManager.findFragmentById.

The new fragment to be added will be created via the FragmentFactory of the FragmentManager.

Parameters
containerViewId: Int Identifier of the container this fragment is to be placed in.
tag: String? = null Optional tag name for the fragment, to later retrieve the fragment with FragmentManager.findFragmentByTag.
args: Bundle? = null Optional arguments to be set on the fragment.
Return
Returns the same FragmentTransaction instance.

add

inline fun <reified F : Fragment> FragmentTransaction.add(
    tag: String,
    args: Bundle? = null
): FragmentTransaction

Add a fragment to the associated FragmentManager without adding the Fragment to any container view.

The new fragment to be added will be created via the FragmentFactory of the FragmentManager.

Parameters
tag: String Tag name for the fragment, to later retrieve the fragment with FragmentManager.findFragmentByTag.
args: Bundle? = null Optional arguments to be set on the fragment.
Return
Returns the same FragmentTransaction instance.

clearFragmentResult

fun Fragment.clearFragmentResult(requestKey: String): Unit

Clears the stored result for the given requestKey.

This clears a result that was previously set a call to setFragmentResult.

If this is called with a requestKey that is not associated with any result, this method does nothing.

Parameters
requestKey: String key used to identify the result

clearFragmentResultListener

fun Fragment.clearFragmentResultListener(requestKey: String): Unit

Clears the stored FragmentResultListener for the given requestKey.

This clears a FragmentResultListener that was previously set a call to setFragmentResultListener.

If this is called with a requestKey that is not associated with any FragmentResultListener, this method does nothing.

Parameters
requestKey: String key used to identify the result

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

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.

createViewModelLazy

@MainThread fun <VM : ViewModel> Fragment.createViewModelLazy(
    viewModelClass: KClass<VM>,
    storeProducer: () -> ViewModelStore,
    factoryProducer: () -> ViewModelProvider.Factory = null
): Lazy<VM>

Helper method for creation of ViewModelLazy, that resolves null passed as factoryProducer to default factory.

findFragment

fun <F : Fragment> View.findFragment(): F

Find a Fragment associated with a View.

This method will locate the Fragment associated with this view. This is automatically populated for the View returned by Fragment.onCreateView and its children.

Calling this on a View that does not have a Fragment set will result in an IllegalStateException

replace

inline fun <reified F : Fragment> FragmentTransaction.replace(
    @IdRes containerViewId: Int,
    tag: String? = null,
    args: Bundle? = null
): FragmentTransaction

Replace an existing fragment that was added to a container. This is essentially the same as calling remove for all currently added fragments that were added with the same containerViewId and then add with the same arguments given here.

The new fragment to place in the container will be created via the FragmentFactory of the FragmentManager.

Parameters
containerViewId: Int Identifier of the container whose fragment(s) are to be replaced.
tag: String? = null Optional tag name for the fragment, to later retrieve the fragment with FragmentManager.findFragmentByTag.
args: Bundle? = null Optional arguments to be set on the fragment.
Return
Returns the same FragmentTransaction instance.

setFragmentResult

fun Fragment.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 androidx.lifecycle.Lifecycle.State.STARTED, the result is stored until one becomes available, or clearFragmentResult is called with the same requestKey.

Parameters
requestKey: String key used to identify the result
result: Bundle the result to be passed to another fragment or null if you want to clear out any pending result.

setFragmentResultListener

inline fun Fragment.setFragmentResultListener(
    requestKey: String,
    crossinline listener: (resultKey: String, bundle: Bundle) -> Unit
): Unit

Sets the FragmentResultListener for a given requestKey. Once this Fragment is at least in the androidx.lifecycle.Lifecycle.State.STARTED state, any results set by setFragmentResult using the same requestKey will be delivered to the FragmentResultListener.onFragmentResult callback. The callback will remain active until this Fragment reaches the androidx.lifecycle.Lifecycle.State.DESTROYED state or clearFragmentResultListener is called with the same requestKey..

Parameters
requestKey: String requestKey used to store the result
listener: (resultKey: String, bundle: Bundle) -> Unit listener for result changes or null to remove any previously registered listener.

setFragmentResultListener

inline fun FragmentResultOwner.setFragmentResultListener(
    requestKey: String,
    lifecycleOwner: LifecycleOwner,
    crossinline listener: (resultKey: String, bundle: Bundle) -> Unit
): Unit

Sets the FragmentResultListener for a given requestKey. Once the given LifecycleOwner is at least in the androidx.lifecycle.Lifecycle.State.STARTED state, any results set by FragmentResultOwner.setFragmentResult using the same requestKey will be delivered to the FragmentResultListener.onFragmentResult callback. The callback will remain active until the LifecycleOwner reaches the androidx.lifecycle.Lifecycle.State.DESTROYED state or a null FragmentResultListener is set for the same requestKey.

Parameters
requestKey: String requestKey used to store the result
lifecycleOwner: LifecycleOwner lifecycleOwner for handling the result
listener: (resultKey: String, bundle: Bundle) -> Unit listener for result changes or null to remove any previously registered listener.

transaction

inline fun FragmentManager.transaction(
    now: Boolean = false,
    allowStateLoss: Boolean = false,
    body: FragmentTransaction.() -> Unit
): Unit

Deprecated.

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

viewModels

@MainThread inline fun <reified VM : ViewModel> Fragment.viewModels(
    noinline ownerProducer: () -> ViewModelStoreOwner = { this },
    noinline factoryProducer: () -> ViewModelProvider.Factory = null
): Lazy<VM>

Returns a property delegate to access ViewModel by default scoped to this Fragment:

class MyFragment : Fragment() {
    val viewmodel: MYViewModel by viewmodels()
}

Custom ViewModelProvider.Factory can be defined via factoryProducer parameter, factory returned by it will be used to create ViewModel:

class MyFragment : Fragment() {
    val viewmodel: MYViewModel by viewmodels { myFactory }
}

Default scope may be overridden with parameter ownerProducer:

class MyFragment : Fragment() {
    val viewmodel: MYViewModel by viewmodels ({requireParentFragment()})
}

This property can be accessed only after this Fragment is attached i.e., after Fragment.onAttach, and access prior to that will result in IllegalArgumentException.