How to click OK on AlertDialog through code?

I use showDialog and dismissDialog in action to display and destroy my dialog. Is there a way to issue a click command in the current dialog box without saving the variable referencing the dialog?

For example, I want to click the "Ok" / "Add" button in a dialog box using code.

+7
source share
3 answers

I have not tested this code, but it should work:

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

Alternatively, if you do not want to save a link to the dialog, but control its configuration, you can extract the code with a click in 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 pressing the OK button programmatically, you can call onPositiveButtonClicked() and dismissDialog(id) . If you need to handle several dialogs, onPositiveButtonClicked take id .

+25
source

I want to click the "Ok" / "Add" button in the dialog using code

Yes, you can do this by getting an instance of POSITIVE BUTTON, and then call performClick() on it. try:

 Button okButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE); okButton.performClick(); //<<< click Button using code 
+4
source

Try the following: -

 AlertDialog.Builder alBuilder = new AlertDialog.Builder(this); alBuilder .setMessage("Do you wamt to exit?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); // Write your code here for Yes } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); // Write your code here for No } }); alBuilder.setCancelable(false); alBuilder.show(); 
-one
source

All Articles