问题描述
假设我们有两个片段:MainFragment
和 SelectionFragment
.第二个是用于选择某个对象的构建,例如一个整数.从第二个片段接收结果有不同的方法,如回调、总线等.
Let's say that we have two fragments: MainFragment
and SelectionFragment
. The second one is build for selecting some object, e.g. an integer. There are different approaches in receiving result from this second fragment like callbacks, buses etc.
现在,如果我们决定使用导航架构组件来导航到第二个片段,我们可以使用以下代码:
Now, if we decide to use Navigation Architecture Component in order to navigate to second fragment we can use this code:
NavHostFragment.findNavController(this).navigate(R.id.action_selection, bundle)
其中 bundle
是 Bundle
的一个实例(当然).如您所见,我们无法访问 SelectionFragment
,我们可以在其中放置回调.问题是,如何使用导航架构组件接收结果?
where bundle
is an instance of Bundle
(of course). As you can see there is no access to SelectionFragment
where we could put a callback. The question is, how to receive a result with Navigation Architecture Component?
推荐答案
他们添加了一个 修复 在 2.3.0-alpha02 版本中.
They have added a fix for this in the 2.3.0-alpha02 release.
如果从 Fragment A 导航到 Fragment B 并且 A 需要 B 的结果:
If navigating from Fragment A to Fragment B and A needs a result from B:
findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<Type>("key")?.observe(viewLifecycleOwner) {result ->
// Do something with the result.
}
如果在Fragment B并且需要设置结果:
If on Fragment B and need to set the result:
findNavController().previousBackStackEntry?.savedStateHandle?.set("key", result)
我最终为此创建了两个扩展:
I ended up creating two extensions for this:
fun Fragment.getNavigationResult(key: String = "result") =
findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<String>(key)
fun Fragment.setNavigationResult(result: String, key: String = "result") {
findNavController().previousBackStackEntry?.savedStateHandle?.set(key, result)
}
这篇关于如何使用导航架构组件从片段中获取结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!