Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a result from fragment using Navigation Architecture Component?

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?

like image 965
Nominalista Avatar asked Jun 08 '18 06:06

Nominalista


People also ask

What is 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.


1 Answers

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) } 
like image 199
LeHaine Avatar answered Oct 08 '22 20:10

LeHaine