类和活动之间通过接口进行通信

cod*_*ler 2 android interface

我想MainActivity使用接口与类进行通信。

public interface MyInterface(){
    public void doAction();
}
Run Code Online (Sandbox Code Playgroud)

在我的 MainActivity 中我将有这段代码:

public class MainActivity extends AppCompatActivity implements MyInterface(){

    //....some more code here

    @Override
    public void doAction() {
        //any code action here
    }

    //....some more code here

}
Run Code Online (Sandbox Code Playgroud)

所以现在,如果我有另一个类(不是 ACTIVITY),我应该如何正确地在类---接口---mainActivity 之间建立链接?

public class ClassB {

    private MyInterface myinterface;
    //........

    //...... how to initialize the interface
}
Run Code Online (Sandbox Code Playgroud)

我对如何初始化和使用 ClassB 中的接口感到困惑

Sar*_*tal 5

在其他类的构造函数中:ClassB,接受接口作为参数并传递 的引用Activity,将该对象保存在您的Activity.

像这样:

public class MainActivity extends AppCompatActivity implements MyInterface()
{
    private ClassB ref; // Hold reference of ClassB directly in your activity or use another interface(would be a bit of an overkill)

    @Override
    public void onCreate (Bundle savedInstanceState) {
        // call to super and other stuff....
        ref = new ClassB(this); // pass in your activity reference to the ClassB constructor!
    }

    @Override
    public void doAction () {
        // any code action here
    }
}

public class ClassB
{
    private MyInterface myinterface;

    public ClassB(MyInterface interface)
    {
        myinterface = interface ;
    }

    // Ideally, your interface should be declared inside ClassB.
    public interface MyInterface
    {
         // interface methods
    }
}
Run Code Online (Sandbox Code Playgroud)

仅供参考,这也是 View 和 Presenter 类在 MVP 设计模式中交互的方式。