Taimoor Khan
Taimoor Khan

Reputation: 667

Receive fragment result in Navigation Component Fragment

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.

Upvotes: 2

Views: 2308

Answers (2)

Taimoor Khan
Taimoor Khan

Reputation: 667

As there is another Fragment(NavHostFragment) between childFragment and ParentFragment in Navigation Component. I have found this here In ChildFragment you have to call

parentFragment?.parentFragmentManager?.setFragmentResult

And in ParentFragment(that has NavHost)

childFragmentManager.setFragmentResultListener

Upvotes: 6

Harry
Harry

Reputation: 386

You can try these:

requireActivity().supportFragmentManager.setFragmentResult
requireActivity().supportFragmentManager.setFragmentResultListener

Upvotes: 2

Related Questions