我有两个 fragment 。 SecondFragment
和 ThirdFragment
。实际上,我使用导航组件在 fragment 之间传递值。像这样:
第二个 fragment :
val action = SecondFragmentDirections.action_secondFragment_to_thirdFragment().setValue(1)
Navigation.findNavController(it).navigate(action)
下面是我如何从 ThirdFragment 读取值:
arguments?.let {
val args = ThirdFragmentArgs.fromBundle(it)
thirdTextView.text = args.value.toString()
}
工作正常。现在我的堆栈是这样的:
ThirdFragment
SecondFragment
是否有任何选项可以使用新的导航组件将值从打开的 ThirdFragment 传递到之前的 SecondFragment? (当 ThirdFragment 完成时)
我知道 onActivityResult,但如果 Nav.Component 提供比我想要的更好的解决方案,请使用它。
谢谢!
最佳答案
这个答案有点晚了,但有人可能会发现它很有用。在导航组件库的更新版本中,现在可以在向后导航时传递数据。
假设栈是这样的
fragment A --> fragment B。
我们现在在 FragmentB
中,我们想在返回 FragmentA
时传递数据。
在 FragmentA
中,我们可以创建一个带有键的观察者:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val navController = findNavController()
// Instead of String any types of data can be used
navController.currentBackStackEntry?.savedStateHandle?.getLiveData<String>("key")
?.observe(viewLifecycleOwner) {
}
}
然后在 FragmentB
中,如果我们通过访问先前的返回堆栈条目更改它的值,它将传播到 FragmentA
并且观察者将收到通知。
val navController = findNavController()
navController.previousBackStackEntry?.savedStateHandle?.set("key", "value that needs to be passed")
navController.popBackStack()
关于android - 带参数的导航组件 .popBackStack(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51326437/