在导航组件片段中接收片段结果



我已经在MainFragment(包含NavHost(中实现了NavHost(Navigation Component(,它的导航中还有另外三个片段(类别片段GalleryFragmentPreviewFragment(

以上三个片段是nav_graph中的sibliing。我想向我们的parentFragment(MainFragment(发送一个模型

我尝试了两种不同的方式将数据发送到parentFragment(MainFragment(

预览Fragment.kt在按钮上单击

parentFragmentManager.setFragmentResult("requestKey", bundleOf("bundleKey" to args.photo.imageUrl))
findNavController().previousBackStackEntry?.savedStateHandle?.set("requestKey", args.photo.imageUrl)

MainFragment.kt0nViewCreated

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
}

我看到过一篇帖子,上面说FragmentManager应该和处理片段结果api一样。

我已经直接尝试过parentFragmentManagerchildFragmentManager

你可以试试这些:

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

因为导航组件中childFragment和ParentFragment之间有另一个Fragment(NavHostFragment(。我在这里找到了这个在ChildFragment中,您必须调用

parentFragment?.parentFragmentManager?.setFragmentResult

在ParentFragment中(具有NavHost(

childFragmentManager.setFragmentResultListener

相关内容

  • 没有找到相关文章

最新更新