android - 使用 Otto 将数据从 Activity 传递到 Fragment

标签 android android-activity android-fragments otto

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

在我的主要 Activity 中

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

在我的 fragment 中

    @Subscribe
    public void onCustomStringChanged(String customString) {
    } 

最佳答案

如果您还为同一类型注册了一个 @Produce 方法,则使用 @Subscribe 注释的方法将被自动调用。

像这样通知新数据 fragment 的最佳方法是在 Activity 上使用 @Produce 方法:

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

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

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

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

关于android - 使用 Otto 将数据从 Activity 传递到 Fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14593086/

相关文章:

java - 图像流中的帧是什么?

java.lang.IllegalStateException : You need to use a Theme. AppCompat 主题(或后代)与此 Activity

android - 如何从 TextView 启动 Activity?

android - 将房间数据库中的唯一约束添加到多列

android - 如何在android的新线程中启动服务

java - Android - 使用 RxAndroid 进行 Robolectric 测试?

android - 从文件加载 AppState 时显示 ProgressDialog

android - 如何在 Fragment 类中加载 WebView?如何在android中加载Webview?

android - fragment 中的 ListView setAdapter,空指针异常

android - 如何选择抽屉导航中的第一项并在应用程序启动时打开 fragment