【问题标题】:How to use one Interfaces with many Classes in Android如何在 Android 中使用一个具有多个类的接口
【发布时间】:2018-09-29 11:00:06
【问题描述】:

假设我有 MainActivity 类,其中我有两个按钮,当按下 B1 时,它会调用该类从接口实现的 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 类按钮调用这些操作类方法

Public class MainActivity extends Activity{
//how to call the methods of those classes by making object of Interface class
} 

【问题讨论】:

  • @NileshRathod 实际上我已经看过提到的链接,但我不太了解。这就是为什么我再次问这个问题。很抱歉,但我不清楚如何从 MainActivity 类调用这两个类方法
  • 在您的主要活动中,您必须像在Operations_class_1 类中那样实现接口。
  • 您需要在 MainActivity 中创建 Operation1 和 Operation2 类的对象。然后在 MainActivity 中实现接口。然后 button1 的 onClick 调用你 method1 和 button2 的 onclick 调用 method2 使用接口对象。

标签: java android android-fragments android-activity interface


【解决方案1】:

//如何通过制作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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-25
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多