androidandroid-fragmentsandroid-activityandroid-jetpackandroid-jetpack-navigation

Using setFragmentResultListener in activity


My container activity handles navigation in some cases like this:

fun navigate(directions: NavDirections, extras: Navigator.Extras? = null) {
            extras?.let { navController.navigate(directions, extras) }
                ?: navController.navigate(directions)
    }

one of the fragments returns some data with:

setFragmentResult("request code", bundleOf())

I would like to get that result in the activity but

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityHomeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        supportFragmentManager.setFragmentResultListener("reqeust code", this) { _, _ ->
            //do something
        }
}

doesn't work. I'm sure the problem is not fragment-side as the same code is used to pass data to other fragments

Any way to do this?


Solution

  • I guess the problem is that you are setting the fragment result in a different fragment manager and not in the support fragment manager

    Can you show more code?

    Is setFragmentResult("request code", bundleOf()) called like this parentFragmentManager.setFragmentResult("request code", bundleOf()?

    Try, requireActivity().supportFragmentManager.setFragmentResult(...)

    If that works then my guess is correct.