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 上单击“确定"?
基础教程推荐
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
