两个 Fragment 之间的 EventBus 通信。没有订户错误

EventBus communication between two Fragments. No subscriber error

我使用 EventBus 在 Activity 和 Fragment 之间毫无问题地进行通信,但是当我厌倦了对两个 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);
}
}

示例片段 B(发件人):

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

问题看起来很简单,但是我想不通

好吧,创建一个简单的模型class,我们称之为NotifyEvent

public class NotifyEvent {
    public int mValue;

    public NotifyEvent(int value){
        this.mValue = value;
    }
}

现在发送和接收应该是这样的

在片段 B 中:

private void sendMessage(int msg){
    EventBus.getDefault().post(new NotifyEvent(msg));
}

在片段A中:

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(NotifyEvent event){
        int msg = event.mValue;
        // do something with msg.
}

详情请前往here

我想通了我的问题。有趣的是,你需要传递一些 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;
}
}

希望对大家有所帮助!