Passing data from Activity to Fragment using Otto

谁说我不能喝 提交于 2019-12-06 07:16:50

问题


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) {
    } 

回答1:


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.



来源:https://stackoverflow.com/questions/14593086/passing-data-from-activity-to-fragment-using-otto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!