Android为什么片段不应该直接相互通信? [英] Android why Fragments should not directly communicate with each other?

查看:146
本文介绍了Android为什么片段不应该直接相互通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有活动A 托管两个主要片段F1和F2 F1 F2 都嵌套了 Fragment ,每个都有它的拥有监听器用于交换数据的界面。

I have an Activity A hosting two main Fragment F1 and F2. Both F1 and F2 have nested Fragment, each with its own Listener interface for exchanging data.

从我对答案的理解这个问题,活动 A

From what I understood from the answer to this question, the activity A:


  • 需要知道由 F1 F2

需要路由 F1 F2 到正确的主片段, F1 F2

needs to route the events generated by the fragments in F1 and F2 to the correct main fragment, F1 or F2.

如果我理解正确,这种方法没有模块化:活动需要知道它所托管的片段( F1 F2 )以及嵌套的片段的所有内容 F1 F2

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.

我说错了吗?当然,我很困惑......

Am I correct? For sure, I am very confused ...

推荐答案

如果你看一下 与其他片段进行交流 教程,它说:

If you look at the Communicating with Other Fragments tutorial, it says that:


所有片段到片段的通信都是通过关联的
活动完成的。两个片段不应该直接通信。

All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

原因是片段 s是流动的&可能淡入和淡出视图的动态UI组件。只有托管活动能够确定是否将 Fragment 添加到用户界面或是否已与其分离。

The reason for this is that Fragments are fluid & dynamic UI components that may fade in and out of view. Only the hosting Activity is capable of determining if a Fragment is added to the UI or has been detached from it.


如果我理解正确,这种方法没有模块性:
活动需要知道关于它们的两个片段的所有内容b $ b主机( F1 F2 )以及嵌套在 F1 <中的片段/ code>和 F2

片段 s是模块化的,因为它们是完全独立的。可重用的UI块。此外,它们是模块化的,因为它们的接口定义明确,并由托管活动明确实现。如果活动实现片段中定义的回调接口,则删除 Fragment 中的任何位置,然后活动选择做什么,具体取决于是否添加了 Fragment 是否附加到用户界面。

The Fragments are "modular" in the sense that they are totally independent & reusable UI blocks. Also, they are "modular" because their interfaces are well defined and explicitly implemented by the hosting Activity. Anywhere you drop that Fragment in, if the Activity implements the callback interface defined in the Fragment, then the Activity "chooses" what to do depending on whether the Fragment is added / attached to the UI or not.

如果我们在这里松散地应用 MVC 的思维方式,那么托管活动作为控制器在两个视图之间进行排序片段。当然这只是一个简单的类比,但希望你能得到这样的结论。

If we loosely apply the MVC way of thinking here, the hosting Activity acts as a controller of sorts between two views which are the Fragments. Of course this is just a loose analogy, but hopefully you get the picture.

进一步的考虑因素:

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

There is an alternative to this approach: a method called getParentFragment() that a nested Fragment can use to get a reference to the "outside" Fragment.

参考文献:

1。 为什么不推荐片段之间的直接沟通?

2. 与其他片段或活动进行通信

3。 片段问题:片段间通信?

这篇关于Android为什么片段不应该直接相互通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆