Android中AlertDialog 点击按钮后不关闭对话框的功能
作者:SoftXJ
本篇文章主要介绍了Android中AlertDialog 点击按钮后不关闭对话框的功能,非常具有实用价值,需要的朋友可以参考下

这里的问题:当我点击确定按钮,也就是 AlertDialog 里的 PositiveButton 的时候,我们需要判断用户是输入是否符合我们的预期,如果不符合通常提示用户重写输入,且不关闭当前的对话框,但上图中点击按钮后会自动的关闭窗口。
先看原来的这个是怎么写的:
private void openDialog() {
LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.change_password_dialog, null);
final EditText originPasswordEt = (EditText) linearLayout.findViewById(R.id.origin_password);
TextView forgetPassword = (TextView) linearLayout.findViewById(R.id.forget_password);
final AlertDialog dialog = new AlertDialog.Builder(getContext())
.setView(linearLayout)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String originPassword = originPasswordEt.getText().toString().trim();
//传到后台
}
})
.create();
dialog.show();
}
虽然图片里和代码的并不是同一个,但问题是一样的
在 setPositiveButton 方法中,即使我们没有调用 dialog.dismiss()
但对话框还是会自动的关闭,就算我们在 onClick 里判断输入的内容,错误的提示也会在窗口关闭后才出现。
在 AlertDialog 提供的 API 中我也没有找到可以设置的地方,如果有还请告知。而我解决这个问题的办法:
final AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setTitle(msg)
.setView(layout)
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setPositiveButton("submit",null)
.setCancelable(true)
.create();
dialog.show();
//为了避免点击 positive 按钮后直接关闭 dialog,把点击事件拿出来设置
dialog.getButton(AlertDialog.BUTTON_POSITIVE)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Pattern pattern = Pattern.compile("[0-9]*");
Matcher matcher = pattern.matcher(editText.getText());
if (!matcher.matches()){
showToast("请输入正确的 ID");
break;
}
dialog.dismiss();
}
}
});
setPositiveButton("submit",null) 监听事件传入 null
在调用 dialog.show() 后再设置 Button 的点击事件,否则 getButton() 会返回空
这样在我们手动调用 dialog.dismiss() 之前,对话框是不会关闭的。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
- Android实现点击AlertDialog上按钮时不关闭对话框的方法
- Android中AlertDialog各种对话框的用法实例详解
- Android使用AlertDialog实现的信息列表单选、多选对话框功能
- Android修改源码解决Alertdialog触摸对话框边缘消失的问题
- Android 自定义AlertDialog对话框样式
- Android对话框AlertDialog.Builder使用方法详解
- ANDROID中自定义对话框AlertDialog使用示例
- android自定义AlertDialog对话框
- Android Alertdialog(实现警告对话框)
- Android开发之AlertDialog实现弹出对话框
