Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

android - 如何防止单击按钮时对话框关闭(How to prevent a dialog from closing when a button is clicked)

I have a dialog with EditText for input.

(我有一个使用EditText输入的对话框。)

When I click the "yes" button on dialog, it will validate the input and then close the dialog.

(当我单击对话框上的“是”按钮时,它将验证输入,然后关闭对话框。)

However, if the input is wrong, I want to remain in the same dialog.

(但是,如果输入错误,我希望保留在同一对话框中。)

Every time no matter what the input is, the dialog should be automatically closed when I click on the "no" button.

(每次无论输入什么,当我单击“否”按钮时,都应自动关闭对话框。)

How can I disable this?

(如何禁用此功能?)

By the way, I have used PositiveButton and NegativeButton for the button on dialog.

(顺便说一句,我在对话框上的按钮上使用了PositiveButton和NegativeButton。)

  ask by user304881 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EDIT: This only works on API 8+ as noted by some of the comments.

(编辑:这仅适用于API 8+,如某些注释所述。)

This is a late answer, but you can add an onShowListener to the AlertDialog where you can then override the onClickListener of the button.

(这是一个较晚的答案,但是您可以在AlertDialog中添加onShowListener,然后在其中可以覆盖按钮的onClickListener。)

final AlertDialog dialog = new AlertDialog.Builder(context)
        .setView(v)
        .setTitle(R.string.my_title)
        .setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick
        .setNegativeButton(android.R.string.cancel, null)
        .create();

dialog.setOnShowListener(new DialogInterface.OnShowListener() {

    @Override
    public void onShow(DialogInterface dialogInterface) {

        Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // TODO Do something

                //Dismiss once everything is OK.
                dialog.dismiss();
            }
        });
    }
});
dialog.show();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...