问题
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