从 Fragment 1.3.0-alpha04
开始,每个 FragmentManager
都会实现 FragmentResultOwner
。这意味着 FragmentManager
可以充当 Fragment 结果的集中存储区。此更改通过设置 Fragment 结果并监听这些结果,而不要求 Fragment 直接引用彼此,让单独的 Fragment 相互通信。
如需将数据从 Fragment B 传回到 Fragment A,请先在接收结果的 Fragment A 上设置结果监听器。在 Fragment A 的 FragmentManager
上调用 setFragmentResultListener()
API,如以下示例所示:
KOTLIN
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)// Use the Kotlin extension in the fragment-ktx artifact
setResultListener("requestKey") {
key, bundle ->// We use a String here, but any type that can be put in a Bundle is supportedval result = bundle.getString("bundleKey")// Do something with the result...}}
![e43038e7c507fc6ac11453e11f6672af.png](https://img-blog.csdnimg.cn/img_convert/e43038e7c507fc6ac11453e11f6672af.png)