Android 为什么 Fragment 不应该直接相互通信?
Android why Fragments should not directly communicate with each other?
我有一个 Activity A
托管两个主要 Fragment F1 and F2
。 F1
和 F2
都嵌套了 Fragment
,每个都有自己的 Listener
接口用于交换数据。
根据我对 this question 的回答的理解, activity A
:
需要知道由 F1
和 F2
托管的片段声明的每个接口
需要将 F1
和 F2
中的片段生成的事件路由到正确的主片段,F1
或 F2
。
如果我理解正确的话,这种方法没有模块化:activity 需要知道它托管的片段(F1
和 F2
)和片段的所有信息嵌套在 F1
和 F2
中。
我说的对吗?当然,我很困惑......
如果你看 Communicating with Other Fragments 教程,它说:
All Fragment-to-Fragment communication is done through the associated
Activity. Two Fragments should never communicate directly.
原因是 Fragment
是流动和动态的 UI 组件,可能会淡入淡出。只有托管 Activity
能够确定 Fragment
是添加到 UI 还是已从中分离。
If I understood correctly, there is no modularity in this approach:
the activity needs to know everything about both the fragments it
hosts (F1
and F2
) and the fragments that are nested in F1
and F2
.
Fragment
是 "modular",因为它们是完全独立且可重用的 UI 块。此外,它们是 "modular",因为它们的接口定义明确并且由托管 Activity
明确实现。在任何地方放置 Fragment
,如果 Activity
实现了 Fragment
中定义的回调接口,那么 Activity
"chooses" 将根据是否Fragment
是否添加/附加到 UI。
如果我们在这里松散地应用 MVC
思维方式,托管 Activity
充当两个 views
之间的 controller
,即 [=10] =]秒。当然这只是一个粗略的类比,但希望你能明白。
进一步考虑:
这种方法还有一个替代方法:一种称为 getParentFragment()
的方法,嵌套的 Fragment
可以使用该方法来获取对 "outside" Fragment
的引用。
参考文献:
1. Why direct communication between fragments is not recommended?.
我有一个 Activity A
托管两个主要 Fragment F1 and F2
。 F1
和 F2
都嵌套了 Fragment
,每个都有自己的 Listener
接口用于交换数据。
根据我对 this question 的回答的理解, activity A
:
需要知道由
F1
和F2
托管的片段声明的每个接口
需要将
F1
和F2
中的片段生成的事件路由到正确的主片段,F1
或F2
。
如果我理解正确的话,这种方法没有模块化:activity 需要知道它托管的片段(F1
和 F2
)和片段的所有信息嵌套在 F1
和 F2
中。
我说的对吗?当然,我很困惑......
如果你看 Communicating with Other Fragments 教程,它说:
All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.
原因是 Fragment
是流动和动态的 UI 组件,可能会淡入淡出。只有托管 Activity
能够确定 Fragment
是添加到 UI 还是已从中分离。
If I understood correctly, there is no modularity in this approach: the activity needs to know everything about both the fragments it hosts (
F1
andF2
) and the fragments that are nested inF1
andF2
.
Fragment
是 "modular",因为它们是完全独立且可重用的 UI 块。此外,它们是 "modular",因为它们的接口定义明确并且由托管 Activity
明确实现。在任何地方放置 Fragment
,如果 Activity
实现了 Fragment
中定义的回调接口,那么 Activity
"chooses" 将根据是否Fragment
是否添加/附加到 UI。
如果我们在这里松散地应用 MVC
思维方式,托管 Activity
充当两个 views
之间的 controller
,即 [=10] =]秒。当然这只是一个粗略的类比,但希望你能明白。
进一步考虑:
这种方法还有一个替代方法:一种称为 getParentFragment()
的方法,嵌套的 Fragment
可以使用该方法来获取对 "outside" Fragment
的引用。
参考文献:
1. Why direct communication between fragments is not recommended?.