I have implemented NavHost(Navigation Component) in MainFragment(that contain
NavHost) and it has three other fragment in it's nav (CategoryFragment,GalleryFragment and PreviewFragment)
Above three fragment are sibliing in nav_graph. I want to send a model to our parentFragment(MainFragment)
I have tried two different ways to send data to parentFragment(MainFragment)
PreviewFragment.kt on Button Click
parentFragmentManager.setFragmentResult("requestKey", bundleOf("bundleKey" to args.photo.imageUrl))
findNavController().previousBackStackEntry?.savedStateHandle?.set("requestKey", args.photo.imageUrl)
MainFragment.kt 0nViewCreated
navController.currentBackStackEntry?.savedStateHandle?.getLiveData<String>("requestKey")?.observe(
viewLifecycleOwner) { result ->
Toast.makeText(requireContext(), "$result in MainFragment", Toast.LENGTH_SHORT).show()
}
childFragmentManager.setFragmentResultListener("requestKey") { requestKey, bundle ->
// We use a String here, but any type that can be put in a Bundle is supported
val result = bundle.getString("bundleKey")
Toast.makeText(requireContext(), "$result in MainFragment", Toast.LENGTH_SHORT).show()
// Do something with the result
}
I have seen post that said FragmentManager should be same to handle fragment result api.
I have tried it parentFragmentManager , childFragmentManager and directly.
CodePudding user response:
You can try these:
requireActivity().supportFragmentManager.setFragmentResult
requireActivity().supportFragmentManager.setFragmentResultListener
CodePudding user response:
In child fragment you don't need to pass parentFragmentManager. As the document says, in child Fragments, you just need setFragmentResult.

So, in the child fragment, where you only need setFragmentResult to send data to the parent Fragment like below:
setFragmentResult("requestKey", bundleOf("bundleKey" to args.photo.imageUrl))
More infomation: Communicating with fragments - Pass results between parent and child fragments
