片段回调与Android中的EventBus [英] Fragment Callbacks vs EventBus in Android

查看:217
本文介绍了片段回调与Android中的EventBus的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经面对这个问题。我的活动是片段容器,所以为了沟通活动和片段我使用通用回调方法。在这种情况下,我的活动必须根据片段计数实现大量的回调接口。

我不喜欢硬编码和不可读代码。在我的情况下,我的类声明可以用几行来列出所有接口。

我试图摆脱这一点。

I have faced with the problem. My Activity is fragment container, so to communicate between activity and fragments I used common Callback approach. In this case my activity has to implement tons of callback interfaces depending on fragment count.
I don't like to hardcode and unreadable code. In my case my class declaration can take several lines to list all interfaces.
I am trying to get rid of this.

另一种方法是使用 EventBus 模式。

在活动

There is another approach is to use EventBus pattern.
In activity

EventBus.getDefault().register(this);

片段

EventBus.getDetault().post(new MyEvent(description));

并在活动中处理多个事件类型。

And handle several event types in activity.

也许会更好地使用EventBus,而不是默认回调方法?

或者也许是我的错,我的活动持有很多

Maybe there will be better to use EventBus here instead default Callback approach ??
Or maybe there is my fault that my activity is holding a lot of fragments (God Object) and it is better to use activities instead Fragment ?

请建议哪种方法更好?

推荐答案

对于简单的一个Activity到一个Fragment层次结构,回调是最简单的决定。但考虑包含Fragment的Activity,并且Fragment包含可滑动的 ViewPager ,ViewPager的每个选项卡都有片段A,B,C。

For simple one Activity to one Fragment hierarchy, callback is simplest decision to go. But think about Activity containing a Fragment, and the Fragment contains swipe-able ViewPager, and each tab of ViewPager has Fragments A,B,C.

片段A,B,C将长途旅行将事件发送到母亲活动,并且当它们在疯狂复杂的Android Activity-Fragment生命周期舞蹈。在这种情况下,像 otto 这样的eventbus可能是一个不错的选择。

The Fragment A,B,C will go to long journey to send event to mother Activity, and it can be lost interface connectivity between Activity and children when they are restored during crazy complex Android Activity-Fragment lifecycle dances. In this case, eventbus like otto can be a good choice.

事件总线方法的缺点是,很难保持事件来自哪里。因此,建议保留几个发件人。

The drawback of event bus approach is, it is hard to maintain where the event is come from. So, keeping a few sender is recommended.

这篇关于片段回调与Android中的EventBus的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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