Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to click 'OK' on an AlertDialog via code?

I use showDialog and dismissDialog in activity to display and destroy my dialog. Is there also a way to issue a click command on the currently displayed dialog without keeping a variable referencing the dialog?

For example, I want to press the 'Ok' / positive button of the dialog via code.

like image 892
Arci Avatar asked May 07 '13 02:05

Arci


2 Answers

I haven't tested this code but it should work:

AlertDialog dialog = ...
dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();

Alternatively, if you don't want to keep a reference to the dialog but are in control of its setup, you could extract the on click code into another method:

AlertDialog.Builder builder = ...
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int which) {
    onPositiveButtonClicked(); 
  }
});

and implement onPositiveButtonClicked() in your Activity. Instead of programatically clicking the OK button you can call onPositiveButtonClicked() and dismissDialog(id). If you need to handle multiple dialogs, have onPositiveButtonClicked take an id parameter.

like image 91
Matt Giles Avatar answered Sep 18 '22 14:09

Matt Giles


If you are using Builder, it's doesn't have the getButton() function. You can try this one

AlertDialog.Builder alBuilder = new AlertDialog.Builder(this);
alBuilder.setMessage("Test Message")
         .setPositiveButton("Yes", null)
         .setNegativeButton("No",null)
alBuilder.setCancelable(false);
AlertDialog alertDialog = alBuilder.show();

Then you can access the button by below code

alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
like image 40
byteC0de Avatar answered Sep 16 '22 14:09

byteC0de