2017-09-14 64 views
1

我有MainActivity,希望通过接口与类进行通信。通过接口的类和活动之间的通信

public interface MyInterface(){ 
    public void doAction(); 
} 

在我的MainActivity我都会有这样的一段代码:

public class MainActivity extends AppCompatActivity implements MyInterface(){ 

    //....some more code here 

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

    //....some more code here 

} 

所以,现在,如果我有另一个类(不活动),我应该如何正确地作出阶级之间的联系---接口--- mainActivity?

public class ClassB { 

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

    //...... how to initialize the interface 
} 

我感到困惑如何在ClassB的

回答

1

初始化和使用的接口在其他类的构造函数: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 
    } 
} 

仅供参考,这也是查看和演示班MVP设计模式是如何相互作用的。

+0

谢谢你,你答案中的代码的最后一部分是我失踪的部分,它运作良好。 – codeKiller

+0

@eddie快乐编码:) –

1
public class MainActivity extends AppCompatActivity implements 
MyInterface 
{ 
    OnCreate() 
    { 
     ClassB classB= new ClassB(this); 
    } 
} 

public class ClassB 
{ 
    private MyInterface myinterface; 

    public ClassB(MyInterface myinterface) 
    { 
     this.myinterface=myinterface; 
    } 

    void anyEvent() // like user click 
    { 
     myinterface.doAction(); 
    } 
}