简体   繁体   English

如何在Java中调用匿名内部类

[英]How to call anonymous inner class in java

In the code, there is an alert box(for logout functionality). 在代码中,有一个警报框(用于注销功能)。 This alert box is created inside a method (ie logout method) and then two onClickListener are anonymously added to it. 在一个方法(即注销方法)内部创建此警报框,然后将两个onClickListener匿名添加到其中。 How can I call these anonymous listeners from outside? 我如何从外部呼叫这些匿名侦听器?

Code: 码:

AlertDialog.Builder builder
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
   public void onClick(DialogInterface dialog, int id) {
      //some logic
   }
}

What I need is to somehow call this onClick method and pass the instance of same dialog box. 我需要以某种方式调用此onClick方法并传递同一对话框的实例。 I have read examples of doing this with reflection, but in those examples anonymous class was a subclass ie return value of 'new' was catched 我已经阅读了使用反射进行此操作的示例,但是在这些示例中,匿名类是一个子类,即捕获了“ new”的返回值

You could make the listener into a field variable. 您可以将侦听器设置为字段变量。

private final DialogInterface.OnClickListener dialogYesListener = new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int id) {
      //some logic
   }
};

AlertDialog.Builder builder
builder.setPositiveButton("Yes", dialogYesListener);

You can't call it if you don't have any reference of that object. 如果没有该对象的任何引用,则无法调用它。
You can do like following: 您可以执行以下操作:

AlertDialog.Builder builder
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener(){
   public void onClick(DialogInterface dialog, int id) {
      //some logic
   }
builder.setPositiveButton("Yes", listener);
}
// now you can call function on if like
listener.SomeFunction()

See JLS 15.9.5. 参见JLS 15.9.5。 Anonymous Class Declarations for more details. 匿名类声明了解更多详细信息。

You have two options: 您有两种选择:

1) Refactor your code to have a reference to an instance of an DialogInterfact.OnClickListener like this: 1)重构您的代码以引用DialogInterfact.OnClickListener的实例,如下所示:

AlertDialog.Builder builder;
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
         //some logic
    }
}


builder.setPositiveButton("Yes", listener);

2) I don't know whether there is such an API, but if yes, you can try to extract listener implementation from a builder. 2)我不知道是否有这样的API,但如果是,则可以尝试从构建器中提取侦听器实现。 Pseudocode should look like this: 伪代码应如下所示:

DialogInterface.OnClickListener listener =
   builder.getPositiveButton().getListener(); //adjust this to a real API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM