假设我们有两个片段:MainFragment
和SelectionFragment
。第二个是用来选择某个对象的,比如一个整数。从第二个片段接收结果有不同的方法,如回调、总线等。
现在,如果我们决定使用导航架构组件来导航到第二个片段,我们可以使用以下代码:
NavHostFragment.findNavController(this).navigate(R.id.action_selection, bundle)
其中bundle
是Bundle
的一个实例(当然)。正如你所看到的,我们不能访问SelectionFragment
,我们可以在那里放置一个回调。问题是,如何使用导航架构组件接收结果?
发布于 2020-06-03 05:42:48
通过对@LeHaine的答案稍作改进,您可以将这些方法用于导航2.3.0-alpha02
或更高版本
fun <T> Fragment.getNavigationResult(key: String) =
findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<T>(key)
fun <T> Fragment.setNavigationResult(result: T, key: String) {
findNavController().previousBackStackEntry?.savedStateHandle?.set(key, result)
}
发布于 2021-12-16 16:33:42
fun <Type> BaseNavigationActivity<*,*,*>.getNavigationResult(key : String, @IdRes viewId: Int) =
this.findNavController(viewId).currentBackStackEntry?.savedStateHandle?.getLiveData<Type>(key)
fun <Type> BaseNavigationActivity<*,*,*>.setNavigationResult(result: Type, key: String, @IdRes viewId: Int){
this.findNavController(viewId).previousBackStackEntry?.savedStateHandle?.set<Type>(key, result)
}
发布于 2021-04-11 02:00:03
只是其他答案的另一种选择...
在一个共享对象(例如: repo)中以MutableShareFlow为核心的EventBus和一个用here描述的观察者
看起来事情正在远离LiveData,朝着流的方向发展。
值得一看。
https://stackoverflow.com/questions/50754523
复制相似问题