Let's say that we have two fragments: MainFragment
and SelectionFragment
. The second one is build for selecting some object, e.g. an integer. There are different approaches in receiving result from this second fragment like callbacks, buses etc.
Now, if we decide to use Navigation Architecture Component in order to navigate to second fragment we can use this code:
NavHostFragment.findNavController(this).navigate(R.id.action_selection, bundle)
where bundle
is an instance of Bundle
(of course). As you can see there is no access to SelectionFragment
where we could put a callback. The question is, how to receive a result with Navigation Architecture Component?
Among other goodies, Android Jetpack comes with the Navigation architecture component, which simplifies the implementation of navigation in Android apps. In this tutorial, you'll add navigation to a simple book-searching app and learn about: Navigation graphs and nested graphs. Actions and destinations.
They have added a fix for this in the 2.3.0-alpha02 release.
If navigating from Fragment A to Fragment B and A needs a result from B:
findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<Type>("key")?.observe(viewLifecycleOwner) {result -> // Do something with the result. }
If on Fragment B and need to set the result:
findNavController().previousBackStackEntry?.savedStateHandle?.set("key", result)
I ended up creating two extensions for this:
fun Fragment.getNavigationResult(key: String = "result") = findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<String>(key) fun Fragment.setNavigationResult(result: String, key: String = "result") { findNavController().previousBackStackEntry?.savedStateHandle?.set(key, result) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With