我有以下情况: 我有一个MainActivity,它包含3个片段(标签)。在我的片段中,我有两个Switch-Toggles,其状态我想通过EventBus发布到托管活动(MainActivity)。 我在片段内的onCreateView中设置了两个onCheckedChangeListener(对于每个切换):
mSwitchPublish.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ListenerEvent switchPub = new ListenerEvent();
switchPub.setSwitchStatePublish(isChecked);
EventBus.getDefault().post(switchPub);
Log.d(TAG, "EVENTBUS: PUB fired " + isChecked);
}
});
mSwitchSubscribe.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ListenerEvent switchSub = new ListenerEvent();
switchSub.setSwitchStateSubscribe(isChecked);
EventBus.getDefault().post(switchSub);
Log.d(TAG, "EVENTBUS: SUB fired " + isChecked);
}
});
在我的 MainActivity 中,我有以下方法:
@Subscribe(threadMode = ThreadMode.MAIN)
public void handlePubSwitch(ListenerEvent switchPub) {
if (switchPub.getSwitchStatePublish()) {
switchPubChecked = true;
Log.d(TAG, "EVENTBUS: PUB receive " + switchPub);
} else {
switchPubChecked = false;
Log.d(TAG, "EVENTBUS: PUB receive " + switchPub);
// do something else
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void handleSubSwitch(ListenerEvent switchSub) {
if (switchSub.getSwitchStateSubscribe()) {
switchSubChecked = true;
Log.d(TAG, "EVENTBUS: SUB received " + switchSub);
// do something
} else {
switchSubChecked = false;
Log.d(TAG, "EVENTBUS: SUB received " + switchSub);
// do something else
}
}
每次我启动应用程序时,都会收到错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: ***, PID: 4645
org.greenrobot.eventbus.EventBusException: Subscriber class ***.fragments.HomeFragment and its super classes have no public methods with the @Subscribe annotation
我还在Stackoverflow中看到了一些类似的主题(还有一些),但我找不到有效的解决方案......