vih*_*kat 6 android android-fragments android-architecture-navigation
我有两个片段。SecondFragment和ThirdFragment。实际上,我使用导航组件在片段之间传递值。像这样:
SecondFragment:
val action = SecondFragmentDirections.action_secondFragment_to_thirdFragment().setValue(1)
Navigation.findNavController(it).navigate(action)
Run Code Online (Sandbox Code Playgroud)
这是我从ThirdFragment读取值的方式:
arguments?.let {
val args = ThirdFragmentArgs.fromBundle(it)
thirdTextView.text = args.value.toString()
}
Run Code Online (Sandbox Code Playgroud)
很好 现在我的堆栈看起来像这样:
ThirdFragment
SecondFragment
Run Code Online (Sandbox Code Playgroud)
是否可以通过新的导航组件将值从打开的ThirdFragment传递到先前的SecondFragment?(当ThirdFragment完成时)
我知道onActivityResult,但是如果Nav.Component提供比我想要的更好的解决方案。
谢谢!
小智 15
刚刚接触到setFragmentResult(),非常好用。有关于此的文档在这里。
如果您正在导航:片段 A -> 片段 B -> 片段 A 将其添加到片段 A:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setFragmentResultListener("requestKey") { requestKey, bundle ->
shouldUpdate = bundle.getBoolean("bundleKey")
}
}
Run Code Online (Sandbox Code Playgroud)
然后在片段B中添加这行代码:
setFragmentResult("requestKey", bundleOf("bundleKey" to "value to pass back"))
// navigate back toFragment A
Run Code Online (Sandbox Code Playgroud)
当您导航回片段 A 时,侦听器将触发,您将能够获取捆绑包中的数据。
Ali*_*ain 11
这个答案有点晚了,但有人可能会发现它很有用。在导航组件库的更新版本中,现在可以在导航时传递数据。
假设堆栈是这样的
片段A --> 片段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) {
}
}
Run Code Online (Sandbox Code Playgroud)
然后在内部,FragmentB如果我们通过访问先前的返回堆栈条目来更改它的值,它将被传播到FragmentA并通知观察者。
val navController = findNavController()
navController.previousBackStackEntry?.savedStateHandle?.set("key", "value that needs to be passed")
navController.popBackStack()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1416 次 |
| 最近记录: |