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

前端 未结 4 1490
执念已碎
执念已碎 2021-01-17 12:35

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 disp

4条回答
  •  被撕碎了的回忆
    2021-01-17 12:49

    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.

提交回复
热议问题