How to click #39;OK#39; on an AlertDialog via code?(如何通过代码在 AlertDialog 上单击“确定?)
问题描述
我在活动中使用 showDialog 和 dismissDialog 来显示和销毁我的对话框.还有没有办法在当前显示的对话框上发出点击命令,而不保留引用对话框的变量?
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 上单击“确定"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何通过代码在 AlertDialog 上单击“确定"?
- Android viewpager检测滑动超出范围 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
