接口列表

时间:2014-12-09 05:34:12

标签: java android interface

我有一个界面MyListner

public interface MyListner{
    public void onOperationComplete();
}

我有两个Activity SignIn和SignUp,它实现了MyListner

public class SignIn extends Activity implements MyListner{
      @Override
      public void onOperationComplete(){
           Log.e("SignIn","Operation Complete");
      }
      @Override
      protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.main);
           Operation.doOperation();
      }
}

public class SignUp extends Activity  implements MyListner{
      @Override    
      public void onOperationComplete(){    
           Log.e("SignUp","Operation Complete");
      }

      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);    
          Operation.doOperation();

     }
 }

在两个Activity的onCreate()里面我在类操作中调用一个静态函数doOperation(),用于通过Operation.doOperation()进行一些操作。

public class Operation{
    publis static void doOperation(){
       ...........
       ...........
       ...........
       //here i want a callback to interface funtion onOperationComplete()
   }
}

我的要求是我希望在实现MyListner的所有类中获得对onOperationComplete()函数的回调

2 个答案:

答案 0 :(得分:3)

像这样制作你的doOperation:

public class Operation{
     publis static void doOperation(MyListener  callBack){
     ...........
      ...........
     ...........
     //here i want a callback to interface funtion onOperationComplete()
        callBack.onOperationComplete();
  }

}

在您的活动中:

public class SignIn extends Activity implements MyListner{
      @Override
      public void onOperationComplete(){
           Log.e("SignIn","Operation Complete");
      }
      @Override
      protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.main);
           Operation.doOperation(this);
      }
}

答案 1 :(得分:0)

您可能想要查找观察者模式

您可以使您的Operation类单例

在Operation class

中添加“Collection listeners”的属性

添加一个名为“addListener(MyListener)”的公共方法,该方法将传递的参数存储到“listeners”属性中

在Activity的onCreate()内,调用

Operation.getInstance().addListener(this);

如果要执行操作,请致电

for(MyListener listener : listeners){
    listener.onOperationComplete();
}