fragment in kotlin using navigation component switch, pass data from frgament B to A

48 views Asked by At

I have two fragments, fragments A and b. There is a variable named city, that sets the default city of the user, then in fragment B, the user can change the city.

I want to use the new city value that is selected from frag B to get the data for the changed city.

But when I'm trying, I am getting the value of new city but default city value from user profile get set all the time.

1

There are 1 answers

0
Milad Mohammadi On

In fragment A, before navigating to the destination fragment, you can set FragmentResultListener as below:

setFragmentResultListener(RESULT_KEY) { _, bundle ->
    val selectedCity = bundle[BUNDLE_DATA_KEY] as String
    // Do any stuff with the selected city
}

findNavController().navigate(ACTION)

Then in the destination fragment, before navigating up to fragment A, set the bundle data this way:

val selectedCity = "New York"
setFragmentResult(RESULT_KEY, bundleOf(BUNDLE_DATA_KEY to selectedCity))
findNavController().navigateUp()