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


当前回答

public class ComentarDialog extends DialogFragment{
private EditText comentario;

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    LayoutInflater inflater = LayoutInflater.from(getActivity());
    View v = inflater.inflate(R.layout.dialog_comentar, null);
    comentario = (EditText)v.findViewById(R.id.etxt_comentar_dialog);

    builder.setTitle("Comentar")
           .setView(v)
           .setPositiveButton("OK", null)
           .setNegativeButton("CANCELAR", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {

               }
           });

    return builder.create();
}

@Override
public void onStart() {
    super.onStart();

    //Obtenemos el AlertDialog
    AlertDialog dialog = (AlertDialog)getDialog();

    dialog.setCanceledOnTouchOutside(false);
    dialog.setCancelable(false);//Al presionar atras no desaparece

    //Implementamos el listener del boton OK para mostrar el toast
    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(TextUtils.isEmpty(comentario.getText())){
               Toast.makeText(getActivity(), "Ingrese un comentario", Toast.LENGTH_SHORT).show();
               return;
            }
            else{
                ((AlertDialog)getDialog()).dismiss();
            }
        }
    });

    //Personalizamos
    Resources res = getResources();

    //Buttons
    Button positive_button = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
    positive_button.setBackground(res.getDrawable(R.drawable.btn_selector_dialog));

    Button negative_button =  dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
    negative_button.setBackground(res.getDrawable(R.drawable.btn_selector_dialog));

    int color = Color.parseColor("#304f5a");

    //Title
    int titleId = res.getIdentifier("alertTitle", "id", "android");
    View title = dialog.findViewById(titleId);
    if (title != null) {
        ((TextView) title).setTextColor(color);
    }

    //Title divider
    int titleDividerId = res.getIdentifier("titleDivider", "id", "android");
    View titleDivider = dialog.findViewById(titleDividerId);
    if (titleDivider != null) {
        titleDivider.setBackgroundColor(res.getColor(R.color.list_menu_divider));
    }
}
}

其他回答

以下是针对所有类型对话框的一些解决方案,包括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方法的计时取决于消息队列。

另一种解决方案

我想从用户体验的角度提出另一个答案。

为什么要在单击按钮时阻止对话框关闭?大概是因为您有一个自定义对话框,用户尚未在其中做出选择或尚未完全填写所有内容。如果他们还没有完成,那么你根本不应该让他们点击肯定按钮。只要禁用它,直到一切就绪。

这里的其他答案提供了许多技巧来覆盖积极的按钮点击。如果这一点很重要的话,安卓系统难道不会提供一个方便的方法吗?他们没有。

相反,Dialogs设计指南显示了这种情况的一个示例。在用户做出选择之前,“确定”按钮将被禁用。根本不需要任何压倒一切的技巧。用户很明显,在继续之前,仍需要做一些事情。

如何禁用正极按钮

有关创建自定义对话框布局的信息,请参阅Android文档。它建议您将AlertDialog放在DialogFragment中。然后,您需要做的就是在布局元素上设置侦听器,以知道何时启用或禁用肯定按钮。

如果自定义对话框具有单选按钮,请使用RadioGroup.OnCheckedChangeListener。如果自定义对话框有复选框,请使用CompoundButton.OnCheckedChangeListener。如果自定义对话框具有EditText,则使用TextWatcher。

正面按钮可以这样禁用:

AlertDialog dialog = (AlertDialog) getDialog();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);

这是一个完整的正在工作的DialogFragment,带有一个禁用的肯定按钮,如上图所示。

import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;

public class MyDialogFragment extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // inflate the custom dialog layout
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.my_dialog_layout, null);

        // add a listener to the radio buttons
        RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.radio_group);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                // enable the positive button after a choice has been made
                AlertDialog dialog = (AlertDialog) getDialog();
                dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
            }
        });

        // build the alert dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(view)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO: use an interface to pass the user choice back to the activity
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        MyDialogFragment.this.getDialog().cancel();
                    }
                });
        return builder.create();
    }

    @Override
    public void onResume() {
        super.onResume();

        // disable positive button by default
        AlertDialog dialog = (AlertDialog) getDialog();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
    }
}

自定义对话框可以从如下活动运行:

MyDialogFragment dialog = new MyDialogFragment();
dialog.show(getFragmentManager(), "MyTag");

笔记

为了简洁起见,我省略了将用户选择信息传递回活动的通信接口。不过,文档显示了如何做到这一点。该按钮在onCreateDialog中仍然为空,因此我在onResume中禁用了它。如果用户切换到另一个应用程序,然后在不关闭对话框的情况下返回,则会再次禁用它。这可以通过取消选择任何用户选项或从onCreateDialog调用Runnable来在下次运行循环中禁用按钮来解决。view.post(newRunnable(){@覆盖公共空运行(){AlertDialogdialog=(AlertDialog)getDialog();dialog.getButton(AlertDialog.BUTTON.POSITIVE).setEnabled(false);}});

相关的

带有一个、两个和三个按钮的Android警报对话框如何在Android警报对话框中显示列表视图?

我找到了另一种方法来实现这一点。。。

步骤1:将对话框打开代码放入方法(或C中的函数)。步骤2:在onClick of yes(您的positiveButton)中,调用此对话框打开如果条件不满足,则递归使用方法(通过使用if…else…)。如下所示:

private void openSave() {
   
    final AlertDialog.Builder builder=new AlertDialog.Builder(Phase2Activity.this);

    builder.setTitle("SAVE")
            .setIcon(R.drawable.ic_save_icon)
            .setPositiveButton("Save", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    
                        if((!editText.getText().toString().isEmpty() && !editText1.getText().toString().isEmpty())){

                                createPdf(fileName,title,file);
                            
                        }else {
                            openSave();
                            Toast.makeText(Phase2Activity.this, "Some fields are empty.", Toast.LENGTH_SHORT).show();
                        }

                    
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
               dialogInterface.dismiss();
            }
        })
            .setCancelable(false)
            .create()
            .show();

}

但这将使对话框消失片刻,并立即再次出现。:)

如果您正在使用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,然后根据需要设置肯定按钮