如何在Android中防止Appcompact AlertDialog在点击积极按钮时自动关闭?

3
我该如何在appcompact7的alertdialog中进行自定义验证呢? 我在alertdialog中有一些输入,所以当我点击确认按钮时,我想要验证条件是否成立,如果条件不成立,我只想显示错误消息而不关闭对话框。 我尝试了这个,但没有帮助。
alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                if (true) {
                                    // Do this and dissmiss
                                } else {
                                    // Do not dismiss the dialog
                                    errormsg.setVisibility(View.VISIBLE);
                                    errormsg.setText("Error");
                                }

                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
1个回答

1
不要在构建器中添加点击监听器。在对话框的onShow()或onStart()方法内添加监听器。
builder.setPositiveButton("Proceed", null);

@Override
    public void onStart() {
        super.onStart();
        final AlertDialog dialog = (AlertDialog) getDialog();

         if (dialog != null) {
            Button positiveButton = dialog.getButton(Dialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                }
            });
        }
    }

无法覆盖 onStart,上面的解决方案使用了 android.app.dialog,我想使用 appcompact。 - Veer3383
2019年:appcompat版本28.0.0与此解决方案完美配合。 - ruX

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接