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.