This question already has answers here:
How to prevent a dialog from closing when a button is clicked
                                
                                    (17个答案)
                                
                        
                                4年前关闭。
            
                    
下面的代码定义了一个带2个按钮的AlertDialog。单击任一按钮将调用正确的onClick方法。实际上,每个方法都只有一个Log语句,但是单击其中任何一个都会导致该对话框被关闭。为什么?

AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setPositiveButton("Dismiss",
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d("MyFragment", "Positive button");
            }
        }).setIcon(android.R.drawable.ic_dialog_info);

builder.setNeutralButton("Send Email",
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d("MyFragment", "Neutral button");
            }
        }).setIcon(android.R.drawable.ic_dialog_info);
builder.setMessage("Some message");
builder.setCancelable(false);

Dialog dialog = builder.create();
dialog.setTitle("Details");
dialog.setCancelable(false);
dialog.show();

最佳答案

该对话框被关闭,因为这是其默认行为。如果希望保留它,则可以覆盖onShowListener并在此处设置适当的按钮单击侦听器。

final AlertDialog dialog = builder.create();
    dialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface d) {
            dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(...);
        }
    });

10-05 19:03