我是接口的新手,我试图做以下事情。我错过了什么?
public class MyAdapter implements ItemManager.DoThisInterface {
...
@Override
doThis() {
// Do things specific to my adapter. Define action hre.
}
}
接口在项目管理器中定义,它不知道需要做什么。适配器应定义操作。
public class ItemManager {
....
private void onCertainEvent() {
doThis(); // do whatever is overriden in adapter.
// this is kind of a placeholder for what i expect to be defined
// in the adapter.
// (this fails to compile because it can't call straight to the interface method)
}
// interface declaration
public interface DoThisInterface {
doThis();
}
}
答案 0 :(得分:0)
您可能需要创建一个对象。
MyAdapter ma=new MyAdapter();
ma.doThis();
调用此方法,您的问题将得到解决。
答案 1 :(得分:0)
您应该在类DoThisInterface
上设置ItemManager
实例,并将其保存在实例字段中,然后使用该实例调用接口方法,如下所示
public class ItemManager {
private DoThisInterface mDoThisInterface;
....
private void onCertainEvent() {
if(mDoThisInterface != null){
mDoThisInterface.doThis();
}
}
public void setDoThisInterface(DoThisInterface doThisInterface){
mDoThisInterface = doThisInterface;
}
// interface declaration
public interface DoThisInterface {
doThis();
}
}