在同一片段的不同实例之间进行通信 [英] Communicate between different instances of same fragment
问题描述
问题如下.让我们有 3 个带有片段的标签:
The problem as follows. Let us have 3 tabs with fragments:
- 标签 1(片段 A).需要将数据发送到 Tab 2.
- 标签 2(片段 B).需要从 Tab 1 接收数据.
- 标签 3(片段 B).已经包含数据.
如您所见,Tab 3 和 Tab 2 包含相同的片段但不同的实例.
As you see Tab 3 and Tab 2 contain the same Fragment but different instances.
如何将数据(不通过参数)发送到 Tab 2?
我尝试过的:
- 在创建片段 B 时通过参数为其设置唯一 ID.
- 为 Fragment B 的两个实例注册相同的
Local Broadcast Receiver
- 将数据从 Fragment A 发送到 Fragment B 及其 ID
- 在片段 B
onReceive()
中检查接收到的 ID 是否等于片段的 ID
- Set the unique ID for Fragment B via arguments when they were created.
- Register same
Local Broadcast Receiver
for both instances of Fragment B - Send data from Fragment A to Fragment B with its ID
- In Fragment B
onReceive()
check if recevied ID equals ID of Fragment
但不幸的是,广播仅发送到 Tab 3.
But unfortunately broadcast was sent to Tab 3 only.
更多信息.
这些选项卡托管在另一个带有 ViewPager
的片段中.那是由于 NavigationDrawer
的组合,它具有与 ViewPager
和 Tabs 相关的片段.
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.
要添加依赖项 - 将 compile '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中
@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() {}
}
在 Fragment A 中发送事件:
And in Fragment A just send the event:
protected EventBus eventBus;
....
eventBus = EventBus.getDefault();
....
eventBus.post(new NewDataEvent());
(并避免在第二个选项卡中处理事件 - 只需在片段实例化期间传递额外参数,如果它必须监听事件)
(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屋!