如何通过代码在 AlertDialog 上单击“确定"?

时间:2023-04-24
本文介绍了如何通过代码在 AlertDialog 上单击“确定"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在活动中使用 showDialogdismissDialog 来显示和销毁我的对话框.还有没有办法在当前显示的对话框上发出点击命令,而不保留引用对话框的变量?

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.

推荐答案

我没有测试过这段代码,但它应该可以工作:

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(); 
  }
});

并在您的 Activity 中实现 onPositiveButtonClicked().您可以调用 onPositiveButtonClicked()dismissDialog(id),而不是以编程方式单击 OK 按钮.如果您需要处理多个对话框,请让 onPositiveButtonClicked 采用 id 参数.

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.

这篇关于如何通过代码在 AlertDialog 上单击“确定"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何使用 xml 布局获取对在自定义对话框中创建的按钮的引用? 下一篇:Android 对话框自行消失

相关文章