【问题标题】:Passing data from Activity to Fragment using Otto使用 Otto 将数据从 Activity 传递到 Fragment
【发布时间】:2013-07-18 18:31:57
【问题描述】:

在我的应用程序中,我将片段动态添加到主活动视图中的容器中。我想知道在添加 Fragment 时使用 Otto 时传递数据的最佳方式是什么。目前这就是我的做法,例如我没有发布我的 CustomObject

在我的主要活动中

    getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, MY_CUSTOM_FRAGMENT).commit();
    BusProvider.getInstance().post(produceCustomString());

在我的片段中

    @Subscribe
    public void onCustomStringChanged(String customString) {
    } 

【问题讨论】:

    标签: android android-activity android-fragments otto


    【解决方案1】:

    如果您还注册了相同类型的@Produce 方法,则将自动调用带有@Subscribe 注释的方法。

    通知此类新数据片段的最佳方法是在活动上使用@Produce 方法:

    @Produce public String produceCustomString() {
      return "Hello, World!";
    }
    

    然后是所有具有@Subscribe 方法的片段:

    @Subscribe public void onCustomStringEvent(String event) {
      // ...
    }
    

    当您注册一个具有此方法的片段时,Otto 将在活动上调用@Produce 方法以获取它将传递给片段方法的最新值。

    【讨论】:

    • 谢谢杰克,这有帮助。实际上我的活动中有@Produce,但在添加片段后我仍然手动调用post。将删除该额外的帖子。
    • 试图编辑答案以将“public void String”替换为“public String”,系统不允许我这样做,说“编辑必须至少为 6 个字符”:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    相关资源
    最近更新 更多