使用 Android 导航将数据传回上一个片段 [英] Pass data back to previous fragment using Android Navigation
问题描述
我已经开始使用 Android 架构组件(导航和安全参数、视图模型)以及 Koin 库.
I've started using Android Architecture Components (Navigation and Safe Args, View Models) along with Koin library.
目前,我在两个片段之间传递参数时遇到问题 - 我需要将字符串值从片段 A 传递到片段 B,在片段 B 中修改该值并将其传递回片段 A.
Currently, I've got a problem with passing arguments between two fragments - I need to pass a string value from fragment A to fragment B, modify this value in fragment B and pass it back to fragment A.
我找到了一种可能的解决方案 - 共享视图模型.不幸的是,这种方法有一个问题,因为我可以在屏幕之间传递和修改值,但是当片段 A 导航到另一个目的地时,共享视图模型中的值仍然存储而不是清除.
I've found one possible solution to my problem - shared view models. Unfortunately, this approach has one problem because I can pass and modify values between screens, but when the fragment A navigate to another destination the value in the shared view model is still stored and not cleared.
Android Navigation 中在片段之间传递和修改数据有什么不同的解决方案吗?我想避免手动清除这个值(当片段 A 被销毁时).
Is there any different solution of passing and modifying data between fragments in Android Navigation? I want to avoid clearing this one value by hand (when the fragment A is destroyed).
推荐答案
Android 刚刚为此发布了一个解决方案;在目的地之间传递数据(导航 2.3.0-alpha02),基本上,在片段 A 中,您观察变量的变化,而在片段 B 中,您在执行 popBackStack()
之前更改该值.
Android just released a solution for this; Passing data between Destinations (Navigation 2.3.0-alpha02), basically, in fragment A you observe changes in a variable and in fragment B you change that value before executing popBackStack()
.
片段 A:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val navController = findNavController();
// We use a String here, but any type that can be put in a Bundle is supported
navController.currentBackStackEntry?.savedStateHandle?.getLiveData<String>("key")?.observe(
viewLifecycleOwner) { result ->
// Do something with the result.
}
}
片段 B:
navController.previousBackStackEntry?.savedStateHandle?.set("key", result)
navController.popBackStack()
这篇关于使用 Android 导航将数据传回上一个片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!