在我的应用程序中,我将 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/