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

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

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

我已经试过:

  • 通过参数设置片段B的唯一ID创建它们的时候。
  • 注册相同的本地广播接收机的片段B的两个实例
  • 发送从片段A的数据片段B,其ID
  • 在片段B 的onReceive()检查recevied 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
  • 但不幸的是广播发送到只有标签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)

    更多推荐

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

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

    发布评论

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

    >www.elefans.com

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