有没有办法阻止AlertDialog无效inputclosures?

我正在使用带有正面和取消button的简单文本字段警报对话框。 我想validation我的警报对话框,并防止如果input无效,完成buttonclosuresAlertDialog。

有没有办法创build一个自定义对话框,以防止PositiveButton onClick()处理程序closures对话框,如果validation失败?

class CreateNewCategoryAlertDialog { final EditText editText; final AlertDialog alertDialog; class PositiveButtonClickListener implements OnClickListener { @Override public void onClick(DialogInterface dialog, int which) { String name = editText.getText().toString(); if(name.equals("")) { editText.requestFocus(); editText.setError("Please enter a name"); // Some code to stop AlertDialog from closing goes here... } else { doSomethingUsefulWithName(); } } } AlertDialog buildAlertDialog(Context context) { return new AlertDialog.Builder(context) .setTitle(context.getString(R.string.enter_name)) .setMessage(context.getString(R.string.enter_name_msg)) .setView(editText) .setPositiveButton(context.getString(R.string.done), new PositiveButtonClickListener()) .setNegativeButton(context.getString(R.string.cancel), null).create(); } } 

Solutions Collecting From Web of "有没有办法阻止AlertDialog无效inputclosures?"

这是我做的。 从技术上讲,它不会在技术上保持对话框打开,它会暂时closures并重新打开它,但最终结果是一样的。

 class MyAlertDialog implements OnDismissListener, OnCancelListener { final private EditText editText; final private AlertDialog alertDialog; final private EventManager eventManager; final private CategorySelector categorySelector; private Boolean canceled; MyAlertDialog(Context context) { editText = new EditText(context); alertDialog = buildAlertDialog(context); alertDialog.setOnDismissListener(this); alertDialog.setOnCancelListener(this); show(); } private AlertDialog buildAlertDialog(Context context) { return new AlertDialog.Builder(context) .setTitle(context.getString(R.string.enter_name)) .setMessage(context.getString(R.string.enter_name)) .setView(editText) .setNeutralButton(context.getString(R.string.save_text), null) .setNegativeButton(context.getString(R.string.cancel_text), null) .create(); } public void show() { canceled = false; alertDialog.show(); } @Override public void onDismiss(DialogInterface dialog) { if(!canceled) { final String name = editText.getText().toString(); if(name.equals("")) { editText.setError("Please enter a non-empty name"); show(); } else { doWhateverYouWantHere(name); } } } @Override public void onCancel(DialogInterface dialog) { canceled = true; } }