在同一片段的不同实例之间进行通信

编程入门 行业动态 更新时间:2024-10-28 07:22:35
本文介绍了在同一片段的不同实例之间进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

问题如下.让我们有 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)

    更多推荐

    在同一片段的不同实例之间进行通信

    本文发布于:2023-08-02 18:04:55,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1279962.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:片段   实例   通信   在同一

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!