[英]How to use one Interfaces with many Classes in Android
假設我有MainActivity類,其中有兩個按鈕,當按下B1時,它將調用該類從Interface實現的所有Operations_class_1方法,並且當我按下B2但使用Operations_class_2時,情況相同
Public interface Myinterface(){
void method1(); void method2() }
Public Operations_class_1 extends Activity implements Interface
{
method1(){
//calculations perform here
}
method2(){
//calculations perform here
}
}
但是我的問題是如何從MainActivity類按鈕調用這些Operations類方法
Public class MainActivity extends Activity{
//how to call the methods of those classes by making object of Interface class
}
//如何通過使Interface類成為對象來調用那些類的方法
在Java中,您可以實例化類(而不是接口),並使用它們實現接口的事實將其稱為該類型。
Public class MainActivity extends Activity {
MyInterface opClass1 = new Operations_class_1();
MyInterface opClass2 = new Operations_class_2();
...
final Button button = findViewById(R.id.b1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
opClass1.method1();
opClass1.method2();
}
});
}
因為您要實例化的類是一個Activity,所以它也具有生命周期以及Activity附帶的所有內容。 我建議您查看本指南: https : //developer.android.com/guide/components/activities/index.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.