我正在尝试对所有对话的基类中的某些事件实现一些常见的逻辑和反应。
在EventBus中注册和取消注册,并在基类中捕获一些事件。
因此,当我尝试实例化派生类的实例时 - EventBus会抛出一个异常,即DerivedClass没有类似onEvent(*)的方法。 我不想在每个派生类中添加一些存根onEvent方法,这不是软件开发的方式。
如果无法使用这种关于继承的方法,那真是太可悲了。
有人面对过吗?
答案 0 :(得分:1)
在注册EvenBus之前,您可以在基类中创建一个受保护的方法(或使用抽象方法的抽象类),您可以在子类中重写(如果需要)。
public class Test extends Fragment{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(doIneedEventBus()){
EventBus.getDefault().register(this);
}
}
@Override
public void onDestroy() {
super.onDestroy();
if(doIneedEventBus()){
EventBus.getDefault().unregister(this);
}
}
protected boolean doIneedEventBus() {
return true;
}
}
儿童班:
public class TestChild extends Test {
@Override
protected boolean doIneedEventBus() {
return false;
}
}
第二个选项:
try {
EventBus.getDefault().register(this);
} catch (Throwable t){
t.printStackTrace();
}
或者您可以等到库中修复此问题 - https://github.com/greenrobot/EventBus/issues/58
答案 1 :(得分:0)
使用与基类兼容的rxbus2库。