从活动传递数据使用奥托到碎片 [英] Passing data from Activity to Fragment using Otto

查看:141
本文介绍了从活动传递数据使用奥托到碎片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序,我动态地添加到片段中的容器主要活动视图。我想知道什么是使用奥托当我们添加片段时,通过数据的最佳方式。目前,这是我怎么做,请例如,在我没有张贴我CustomObject

在我的主要活动

  getSupportFragmentManager()的BeginTransaction()
                    。新增(R.id.fragment_container,MY_CUSTOM_FRAGMENT).commit();
    。BusProvider.getInstance()后(produceCustomString());
 

在我的片段

  @Subscribe
    公共无效onCustomStringChanged(字符串customString){
    }
 

解决方案

方法标注 @Subscribe 将自动被调用,如果你也有一个 @Produce 法注册的相同类型的。

告知新的数据碎片一样,这是你有活性的 @Produce 方法,最好的方法:

  @Produce公共字符串produceCustomString(){
  返回你好,世界!;
}
 

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

  @Subscribe公共无效onCustomStringEvent(String事件){
  // ...
}
 

当您注册一个片段,它有这种方法,奥托将拜会活动的 @Produce 方法来获得,它会传递给片段的方法中的最新值。

In my application I'm adding Fragments dynamically to the container in main activity view. I would like to know what is the best way to pass data when using Otto when we add Fragment. Currently this is how I'm doing it, please in example I'm not posting my CustomObject

Inside My Main Activity

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

Inside My Fragment

    @Subscribe
    public void onCustomStringChanged(String customString) {
    } 

解决方案

Methods annotated with @Subscribe will automatically be called if you also have a @Produce method for the same type registered.

The best way to inform new fragments of data like this is you have an @Produce method on the activity:

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

And then all your fragments which have @Subscribe methods:

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

When you register a fragment which has this method, Otto will call the @Produce method on the activity to get the latest value which it will pass to the fragment's method.

这篇关于从活动传递数据使用奥托到碎片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆