我有一个对话框与EditText进行输入。当我单击对话框上的“是”按钮时,它将验证输入,然后关闭对话框。但是,如果输入错误,我希望保持在同一对话框中。每次无论输入是什么,当我单击“否”按钮时,对话框都会自动关闭。如何禁用此功能?顺便说一句,我在对话框中使用了PositiveButton和NegativeButton。


当前回答

受汤姆的回答启发,我认为这里的想法是:

在创建对话框期间将onClickListener设置为null然后在显示对话框后设置onClickListener。

您可以像Tom一样重写onShowListener。或者,您可以

调用AlertDialog的show()后获取按钮按如下方式设置按钮的onClickListener(我认为稍微可读一些)。

代码:

AlertDialog.Builder builder = new AlertDialog.Builder(context);
// ...
final AlertDialog dialog = builder.create();
dialog.show();
// now you can override the default onClickListener
Button b = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Log.i(TAG, "ok button is clicked");
        handleClick(dialog);
    }
});

其他回答

如果您正在使用DialogFragment,这是处理Dialog的推荐方法。

AlertDialog的setButton()方法(我认为AlertDialogBuilder的setPositiveButton(()和setNegativeButton()也是如此)所发生的事情是,您使用它设置的按钮(例如AlertDialog.button_POSITIVE)在按下时实际上会触发两个不同的OnClickListener对象。

第一个是DialogInterface.OnClickListener,它是setButton()、setPositiveButton(()和setNegativeButton()的参数。

另一个是View.OnClickListener,它将被设置为在按下任何按钮时自动关闭AlertDialog,并且由AlertDialog自身设置。

您可以做的是使用带有null的setButton()作为DialogInterface.OnClickListener来创建按钮,然后在View.OnClick Listener中调用自定义操作方法。例如,

@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
    AlertDialog alertDialog = new AlertDialog(getActivity());
    // set more items...
    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", null);

    return alertDialog;
}

然后,您可以在DialogFragment的onResume()方法中重写默认AlertDialog的按钮View.OnClickListener(否则将关闭对话框):

@Override
public void onResume()
{
    super.onResume();
    AlertDialog alertDialog = (AlertDialog) getDialog();
    Button okButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
    okButton.setOnClickListener(new View.OnClickListener() { 
        @Override
        public void onClick(View v)
        {
            performOkButtonAction();
        }
    });
}

private void performOkButtonAction() {
    // Do your stuff here
}

您需要在onResume()方法中设置此值,因为getButton()将返回null,直到显示对话框!

这将导致您的自定义操作方法只被调用一次,默认情况下对话框不会被关闭。

科特林

val dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_userinput, null)
        val dialogBuilder = MaterialAlertDialogBuilder(requireContext(), R.style.AlertDialogTheme)
   
        dialogBuilder.setView(dialogView)
        dialogBuilder.setCancelable(false)
        dialogBuilder.setPositiveButton("send",null)
        dialogBuilder.setNegativeButton("cancel") { dialog,_ ->
        dialog.dismiss()
        }


        val alertDialog = dialogBuilder.create()
        alertDialog.show()

        val positiveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
        positiveButton.setOnClickListener {
            val myInputText = dialogView.etxt_userinput.text.toString().trim()
            if(myInputText.isNotEmpty()){
             //Do something
            }else{
                //Prompt error
                dialogView.etxt_userinput.error = "Please fill this"
            }
        }

我们只需使用dialogBuilder创建一个AlertDialog,然后根据需要设置肯定按钮

如果你使用的是材料设计,我建议你查看材料对话框。它为我修复了几个与当前打开的Android bug相关的问题(参见78088),但最重要的是,对于这个问题,它有一个autoDismiss标志,可以在使用生成器时设置。

使用此代码,您可以防止单击肯定按钮时对话框关闭。此外,您还可以使用否定按钮实现相同的功能。

    final AlertDialog alertDialog = alertDialogBuilder
            .setCancelable(false)
            .setTitle("TITLE");
            .setPositiveButton("OK", null)
            .setNegativeButton("CANCEL",
                    (dialog, id) -> {
                        dialog.cancel();
                    })
            .show();
    Button positiveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
    positiveButton.setOnClickListener(v -> {
         // check whatever you want
         if(checkMyCondition())
             dialog.cancel();
    })

以下是针对所有类型对话框的一些解决方案,包括AlertDialog.Builder的解决方案,该解决方案可以在所有API级别上工作(低于API 8,而这里的另一个答案则不适用)。有使用AlertDialog.Builder、DialogFragment和DialogPreference的AlertDialog解决方案。

下面的代码示例显示了如何覆盖默认的公共按钮处理程序,并防止这些不同形式的对话框关闭对话框。所有示例都显示了如何防止肯定按钮关闭对话框。

注意:对于那些需要更多详细信息的人来说,下面的示例描述了基本android类的对话框关闭是如何在后台工作的,以及为什么选择以下方法


AlertDialog.Builder-显示后立即更改默认按钮处理程序()

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Test for preventing dialog close");
builder.setPositiveButton("Test", 
        new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                //Do nothing here because we override this button later to change the close behaviour. 
                //However, we still need this because on older versions of Android unless we 
                //pass a handler the button doesn't get instantiated
            }
        });
final AlertDialog dialog = builder.create();
dialog.show();
//Overriding the handler immediately after show is probably a better approach than OnShowListener as described below
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
      {            
          @Override
          public void onClick(View v)
          {
              Boolean wantToCloseDialog = false;
              //Do stuff, possibly set wantToCloseDialog to true then...
              if(wantToCloseDialog)
                  dialog.dismiss();
              //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
          }
      });
      

DialogFragment-重写onResume()

@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setMessage("Test for preventing dialog close");
    builder.setPositiveButton("Test", 
        new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                //Do nothing here because we override this button later to change the close behaviour. 
                //However, we still need this because on older versions of Android unless we 
                //pass a handler the button doesn't get instantiated
            }
        });
    return builder.create();
}

//onStart() is where dialog.show() is actually called on 
//the underlying dialog, so we have to do it there or 
//later in the lifecycle.
//Doing it in onResume() makes sure that even if there is a config change 
//environment that skips onStart then the dialog will still be functioning
//properly after a rotation.
@Override
public void onResume()
{
    super.onResume();    
    final AlertDialog d = (AlertDialog)getDialog();
    if(d != null)
    {
        Button positiveButton = (Button) d.getButton(Dialog.BUTTON_POSITIVE);
        positiveButton.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        Boolean wantToCloseDialog = false;
                        //Do stuff, possibly set wantToCloseDialog to true then...
                        if(wantToCloseDialog)
                            d.dismiss();
                        //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
                    }
                });
    }
}

DialogPreference-覆盖showDialog()

@Override
protected void onPrepareDialogBuilder(Builder builder)
{
    super.onPrepareDialogBuilder(builder);
    builder.setPositiveButton("Test", this);   //Set the button here so it gets created
}

@Override
protected void showDialog(Bundle state)
{       
    super.showDialog(state);    //Call show on default first so we can override the handlers

    final AlertDialog d = (AlertDialog) getDialog();
    d.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
            {            
                @Override
                public void onClick(View v)
                {
                    Boolean wantToCloseDialog = false;
                    //Do stuff, possibly set wantToCloseDialog to true then...
                    if(wantToCloseDialog)
                        d.dismiss();
                    //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
                }
            });
}

方法说明:

通过查看Android源代码,AlertDialog默认实现通过向OnCreate()中的所有实际按钮注册公共按钮处理程序来工作。单击按钮时,通用按钮处理程序会将单击事件转发给您在setButton()中传递的任何处理程序,然后调用该处理程序会关闭对话框。如果希望在按下其中一个按钮时阻止对话框关闭,则必须替换按钮实际视图的通用按钮处理程序。因为它是在OnCreate()中分配的,所以必须在调用默认的OnCreate(()实现后替换它。在show()方法的过程中调用OnCreate。您可以创建一个自定义对话框类,并重写OnCreate()以调用super.OnCreate(),然后重写按钮处理程序,但是如果您创建了自定义对话框,则无法免费获得Builder,在这种情况下,有什么意义?因此,按照对话框的设计方式使用对话框,但同时控制何时关闭对话框,一种方法是首先调用dialog.Show(),然后使用dialog.getButton()获取对按钮的引用,以覆盖单击处理程序。另一种方法是使用setOnShowListener()并实现查找按钮视图并替换OnShowListen中的处理程序。两者之间的功能差异“几乎”为零,这取决于最初创建对话框实例的线程。通过查看源代码,onShowListener被发送到创建该对话框的线程上运行的处理程序的消息调用。所以,由于OnShowListener是由发布在消息队列上的消息调用的,所以从技术上讲,调用侦听器可能会在显示完成后延迟一段时间。因此,我认为最安全的方法是首先调用show.Dialog(),然后立即在同一执行路径中替换按钮处理程序。由于调用show()的代码将在主GUI线程上运行,这意味着在该线程上执行任何其他代码之前,都将先执行您跟随show()执行的代码,而OnShowListener方法的计时取决于消息队列。