問題描述
我在活動中使用 showDialog
和 dismissDialog
來顯示和銷毀我的對話框.還有沒有辦法在當前顯示的對話框上發(fā)出點擊命令,而不保留引用對話框的變量?
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.
推薦答案
我沒有測試過這段代碼,但它應(yīng)該可以工作:
I haven't tested this code but it should work:
AlertDialog dialog = ...
dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
或者,如果您不想保留對對話框的引用但可以控制其設(shè)置,則可以將點擊代碼提取到另一個方法中:
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 中實現(xiàn) onPositiveButtonClicked()
.您可以調(diào)用 onPositiveButtonClicked()
和 dismissDialog(id)
,而不是以編程方式單擊 OK 按鈕.如果您需要處理多個對話框,請讓 onPositiveButtonClicked
采用 id
參數(shù).
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.
這篇關(guān)于如何通過代碼在 AlertDialog 上單擊“確定"?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!