Ziem My personal blog

How to start a Fragment for a result?

Getting a result from a Fragment is almost identical to the startActivityForResult, setResult, and onActivityResult combo.

In the 1.3.0-alpha04 version of the AndroidX Fragment library, Google introduced new APIs that allow passing data between Fragments.

Added support for passing results between two Fragments via new APIs on FragmentManager. This works for hierarchy fragments (parent/child), DialogFragments, and fragments in Navigation and ensures that results are only sent to your Fragment while it is at least STARTED. (b/149787344)

Thanks to the Fragment Result API, FragmentManager gained two new methods:

How to use it?

In FragmentA, set up FragmentResultListener in the onCreate method:

setFragmentResultListener("request_key") { requestKey: String, bundle: Bundle ->
    val result = bundle.getString("your_data_key")
    // do something with the result
}

In FragmentB, add this code to return the result:

val result = Bundle().apply {
    putString("your_data_key", "Hello!")
}
setFragmentResult("request_key", result)

Start FragmentB e.g. by using:

findNavController().navigate(NavGraphDirections.yourActionToFragmentB())

To close / finish FragmentB call:

findNavController().navigateUp()

Now, your FragmentResultListener will be notified, and you will receive your result.

You can use other methods to achieve something similar:

* I’m using fragment-ktx to simplify the code above.