编程语言
首页 > 编程语言> > java – Android为什么Fragments不应该直接相互通信?

java – Android为什么Fragments不应该直接相互通信?

作者:互联网

我有一个活动A主持两个主要片段F1和F2. F1和F2都有嵌套的Fragment,每个都有自己的Listener接口用于交换数据.

根据我从答案中理解的this question,活动A:

>需要知道由F1和F2托管的片段声明的每个单独接口
>需要将F1和F2中碎片生成的事件路由到正确的主片段F1或F2.

如果我理解正确,这种方法就没有模块性:活动需要知道它所托管的片段(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.

原因是片段是流动的和可能淡入和淡出视图的动态UI组件.只有托管活动能够确定是否已将片段添加到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.

碎片是“模块化的”,因为它们是完全独立的.可重用的UI块.此外,它们是“模块化的”,因为它们的接口定义明确,并由托管活动明确实现.在删除Fragment的任何地方,如果Activity实现了Fragment中定义的回调接口,那么Activity将“选择”做什么,具体取决于是否将片段添加/附加到UI.

如果我们在这里松散地应用MVC思维方式,托管活动充当两个视图之间的分类控制器,即Fragments.当然,这只是一个简单的比喻,但希望你能得到它.

进一步考虑:

这种方法有一种替代方法:一个名为getParentFragment()的方法,嵌套的Fragment可以使用它来获取对“外部”片段的引用.

参考文献:

1. Why direct communication between fragments is not recommended?.

2. Communicating with other fragments or to activity.

3. Fragment question: inter-fragment communication?.

标签:java,android,interface,android-fragments,modularity
来源: https://codeday.me/bug/20190519/1137906.html