Receive fragment result in Navigation Component Fragment
Asked Answered
O

2

1

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.

Odum answered 15/1, 2022 at 12:0 Comment(1)
Have you tried safeArgs for sending data?.. Here are the supported typesBaird
O
5

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
Odum answered 16/1, 2022 at 7:38 Comment(0)
M
2

You can try these:

requireActivity().supportFragmentManager.setFragmentResult
requireActivity().supportFragmentManager.setFragmentResultListener
Merril answered 15/1, 2022 at 12:25 Comment(1)
I know this answer didn't answer the current question. But it answered my scenario where the listener was not getting any results when I try to communicate from fragment to an activity. In the fragment, I was using just setFragmentResult to send the result and it didn't work. But when I used requireActivity().supportFragmentManager.setFragmentResult, it worked all of a sudden. I've no idea why this is the case.Travis

© 2022 - 2024 — McMap. All rights reserved.