在片段导航组件之间传递数据的更好方法? [英] Better way to pass data between Fragments Navigation Component?
问题描述
在导航组件中的片段之间传递数据很容易.假设从 A
到 B
,只需使用 SafeArgs
设置 arguments
,就可以完成.
Passing data between Fragments in Navigation Component is easy. Say going from A
to B
you just set arguments
with SafeArgs
and you are done.
但是,当将数据从 B
传递回 A
时,它变得棘手.
But, it gets tricky when passing data from B
back to A
.
根据文档,我们可以使用 SharedViewModel
效果很好.但是我正在寻找更好的方法将数据从 B
传递回 A
.
According to documentation, we can use SharedViewModel
which is works well. But I am looking for better way of passing data back to A
from B
.
使用 SharedViewModel
的问题是,您必须为需要传递数据的每个片段对创建 SharedViewModel
.
The problem of using SharedViewModel
is, you have to create SharedViewModel
for every fragment pair that you need to pass data.
有什么建议吗?如果您可以考虑使用任何注释处理方法,欢迎您提出建议.
Any suggestions? If any annotation-processing method you can think about, you are more than welcome to recommend.
推荐答案
如果您不想使用 SharedViewModel
方式,则可以采用下一种方法:
If you do not want to use SharedViewModel
way, you can follow the next approach:
1-为您的 Details Fragment
定义一个委托.(该代表必须实现 Serializable
或 Parcelable
:
1- Define a delegate for your Details Fragment
. (This delegate have to implement Serializable
or Parcelable
:
interface DetailsFragmentDelegate: Serializable {
fun onSomething1(someData1: SomeData1)
fun onSomething2(someData2: SomeData2)
}
2- 将委托添加到 nav_graph.xml
3- 将委托传递给您的 Details Fragment
时,通过您的 Base Fragment
定位到目的地:
3- Pass the delegate to your Details Fragment
when navigating to its destination by your Base Fragment
:
findNavController().navigate(
BaseFragmentDirections.actionBaseFragmentToDetailsFragment(
object: DetailsFragmentDelegate {
// override delegate methods
}
)
)
4- 在 Details Fragment
中获取委托参数,并将数据传递回您需要的位置:
4- Get the delegate argument in Details Fragment
and pass the data back wherever you need:
....
delegate.onSomething1(data1)
....
delegate.onSomething2(data2)
....
我不确定是否有更好的方法,但是它正在起作用...
I am not sure whether there is a better way or not, but it's working...
这篇关于在片段导航组件之间传递数据的更好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!