【问题标题】:How to prevent automatic dismiss of Appcompact AlertDialog on positive button click in Android?如何防止在Android中单击肯定按钮时自动关闭Appcompat AlertDialog?
【发布时间】:2016-03-02 18:02:52
【问题描述】:

如何在 appcompact7 alertdialog 中进行自定义验证? 我的警报对话框中有一些输入,所以当我单击肯定按钮时,我想验证条件是否为真,以防条件返回假,我只想显示错误消息并且不应该关闭对话框。

试过this,没有帮助

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

【问题讨论】:

    标签: android android-alertdialog android-appcompat


    【解决方案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
    • 2019: appcompat version 28.0.0 非常适合这个解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-23
    • 1970-01-01
    • 2012-11-24
    • 2014-12-24
    • 2021-11-24
    • 2022-01-06
    相关资源
    最近更新 更多