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 .
Matt giles
source share