2017-09-14 46 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(); 
    } 
}