简体   繁体   中英

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. 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. 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

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. 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:

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. Pseudocode should look like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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