同一片段的不同实例之间进行通信 [英] Communicate between different instances of same fragment

查看:264
本文介绍了同一片段的不同实例之间进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题如下。让我们有3个卡口与片段:

The problem as follows. Let us have 3 tabs with fragments:


  • 标签1(片段A)。需要将数据发送到表2。

  • 标签2(片段B)。需要从标签1接收数据。

  • 标签3(片段B)。已经包含数据。

正如你看到标签3和表2包含相同的片段,但不同的实例。

As you see Tab 3 and Tab 2 contain the same Fragment but different instances.

我如何发送数据(不通过参数)精确表2?

我已经试过:


  1. 通过参数设置片段B的唯一ID创建它们的时候。

  2. 注册相同的本地广播接收机的片段B的两个实例

  3. 发送从片段A的数据片段B,其ID

  4. 在片段B 的onReceive()检查recevied ID等于片段的ID

  1. Set the unique ID for Fragment B via arguments when they were created.
  2. Register same Local Broadcast Receiver for both instances of Fragment B
  3. Send data from Fragment A to Fragment B with its ID
  4. In Fragment B onReceive() check if recevied ID equals ID of Fragment

但不幸的是广播发送到只有标签3。

But unfortunately broadcast was sent to Tab 3 only.

编辑:的更多信息。

这些标签是另一片段内主办了 ViewPager 。那是因为 NavigationDrawer 的组合,与 ViewPager ,并在问题中提到的标签片段。

Those tabs are hosted inside another fragment with ViewPager. Thats due to combination of NavigationDrawer which has fragment with ViewPager and Tabs mentioned in question.

推荐答案

我建议引进 EventBus 在您的应用程序。

I'd suggest to introduce EventBus in your app.

要添加的依赖 - 添加编译。'de.greenrobot:eventbus:2.4.0 进入你的依赖列表

To add dependency - add compile 'de.greenrobot:eventbus:2.4.0' into your list of dependencies.

然后,您只需订阅你的第三个选项卡的片段,从第一个片段监听事件。

Then, you just subscribe your third tab's fragment to listen to event from the first fragment.

事情是这样的:在片段B

Something like this: in Fragment B

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    eventBus.register(this);
}

@Override
public void onDetach() {
    eventBus.unregister(this);
    super.onDetach();
}

@SuppressWarnings("unused") // invoked by EventBus
public void onEventMainThread(NewDataEvent event) {
    // Handle new data
}

NewDataEvent.java

NewDataEvent.java

public class NewDataEvent extends EventBase {
    public NewDataEvent() {}
}

而在片段A只发送事件:

And in Fragment A just send the event:

protected EventBus eventBus;
....
eventBus = EventBus.getDefault();
....
eventBus.post(new NewDataEvent());

(并避免在第二Tab处理事件 - 只是片段化期间,通过额外的参数,如果有听的事件)

(and to avoid handling event in 2nd tab - just pass extra parameter during instantiation of fragment, if it has to listen to the event)

这篇关于同一片段的不同实例之间进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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