单击按钮时如何防止对话框关闭 [英] How to prevent a dialog from closing when a button is clicked

查看:271
本文介绍了单击按钮时如何防止对话框关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与 EditText 的对话框输入。当我单击对话框上的是按钮时,它将验证输入,然后关闭对话框。但是,如果输入错误,我想保留在同一个对话框中。每次无论输入什么,当我点击否按钮时,对话框应该自动关闭。如何禁用此功能?顺便说一下,我已经在对话框上使用了PositiveButton和NegativeButton按钮。

I have a dialog with EditText for input. 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.

推荐答案

编辑:这只适用于API 8+ br>

这是一个迟到的答案,但您可以向AlertDialog添加一个onShowListener,然后您可以覆盖按钮的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 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 dialog) {

        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();
            }
        });
    }
});

这篇关于单击按钮时如何防止对话框关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆