如何prevent自闭的对话框单击按钮时自闭、对话框、单击、按钮

2023-09-11 10:32:27 作者:执着 Paranoid

我有一个的EditText 输入对话框。当我点击Yes按钮上的对话框,它会验证输入,然后关闭对话框。然而,如果输入是错误的,我想保持在相同的对话。每次不管输入什么,对话框会自动当我点击按钮关闭。如何禁用呢?顺便说一句,我已经使用PositiveButton和NegativeButton上对话框按钮。任何帮助将AP preciated!

I have a dialog with EditText for input. When I click 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 button. How can I disable this? By the way, I have used PositiveButton and NegativeButton for the button on dialog. Any Help will be appreciated!

推荐答案

编辑:此的API 8+所指出的一些评论只有作品 - 这是一个迟到的答案,但你可以添加一个onShowListener到AlertDialog,然后可在覆盖按钮的onClickListener。

This only works on API 8+ as noted by some of the comments. This is a late answer, but you can add an onShowListener to the AlertDialog where you can then override the onClickListener of the button.

final AlertDialog d = 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();

d.setOnShowListener(new DialogInterface.OnShowListener() {

    @Override
    public void onShow(DialogInterface dialog) {

        Button b = d.getButton(AlertDialog.BUTTON_POSITIVE);
        b.setOnClickListener(new View.OnClickListener() {

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

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