【问题标题】:Confused about Interfaces. How do I call an interface method in one class and define it in another?对接口感到困惑。如何在一个类中调用接口方法并在另一个类中定义它?
【发布时间】:2015-05-18 04:30:07
【问题描述】:

我是接口新手,我正在尝试执行以下操作。我错过了什么?

public class MyAdapter implements ItemManager.DoThisInterface {
    ...
    @Override
    doThis() {
        // Do things specific to my adapter. Define action hre.
    }
}

接口是在Item Manager中定义的,不知道需要做什么。适配器应该定义动作。

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();
    }
}

【问题讨论】:

    标签: android interface callback


    【解决方案1】:

    您可能需要创建一个对象。

    MyAdapter ma=new MyAdapter();
    ma.doThis();
    

    拨打此电话,您的问题将得到解决。

    【讨论】:

    • 我不希望适配器调用“doThis”。我希望它在适配器中定义,但我希望 ItemManager 调用该方法。
    【解决方案2】:

    你应该在类ItemManager上设置一个DoThisInterface实例,并保存在实例字段中,然后使用实例调用接口方法,像这样

    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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-18
      • 2021-04-08
      • 2014-06-06
      • 2019-04-12
      • 1970-01-01
      • 2020-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多