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

How to click #39;OK#39; on an AlertDialog via code?(如何通过代码在 AlertDialog 上单击“确定?)
本文介绍了如何通过代码在 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 上单击“确定"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How To Create a Rotating Wheel Control?(如何创建转轮控件?)
How to avoid restarting activity when orientation changes on Android(如何在 Android 上的方向更改时避免重新启动活动)
Screen orientation lock(屏幕方向锁定)
Strange behavior with android orientation sensor(android方向传感器的奇怪行为)
Android: Rotate image in imageview by an angle(Android:将imageview中的图像旋转一个角度)
Activity restart on rotation Android(旋转Android上的活动重启)