我使用EventBus在Activity和Fragment之间进行通信没有问题,但是当我厌倦了用两个片段做同样的事情时,EventBus通知我没有给定事件的订阅者。以下是从FragmentB向订阅的FragmentA发送事件的示例:
示例FragmentA(接收方,它没有收到消息):
public class FragmentA extends Fragment {
private View mView;
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(int msg) {/* Do something */};
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.a_fragment_layout, container, false);
EventBus.getDefault().register(this);
return mView;
}
@Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
}
示例FragmentB(发件人):
public class FragmentB extends Fragment {
private View mView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.b_fragment_layout, container, false);
sendMessage(1);
return mView;
}
private void sendMessage(int msg){
EventBus.getDefault().post(msg);
}
}
我得到的错误:
No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent
问题似乎很简单,但我无法弄明白。
答案 0 :(得分:2)
好吧,创建一个简单的模型类,我们称之为NotifyEvent
public class NotifyEvent {
public int mValue;
public NotifyEvent(int value){
this.mValue = value;
}
}
现在发送和接收应该像
FragmentB中的:
private void sendMessage(int msg){
EventBus.getDefault().post(new NotifyEvent(msg));
}
FragmentA中的:
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(NotifyEvent event){
int msg = event.mValue;
// do something with msg.
}
有关详细信息,请转到here
答案 1 :(得分:0)
我发现了我的问题。有趣的是,但是你需要传递一些MessageEvent对象而不是int或其他原始类型。我所做的只是发布一个自定义的MessageEvent对象,它包含必需的参数而不是原始整数:
EventBus.getDefault().post(new SomeObject(9));
而不是
EventBus.getDefault().post(9);
POJO示例:
public class SomeObject {
private int mTime;
public SomeObject(int time){
this.mTime = time;
}
public int getTime() {
return mTime;
}
public void setTime(int time) {
this.mTime = time;
}
}
希望它会对某人有所帮助!