AlertDialogHelper.java文件
package com.appCode.XXXXXX;
import android.content.DialogInterface;
import android.util.Log;
import java.lang.reflect.Field;
/**
* 用于设置AlertDialog点击PositiveButton、NegativeButton、NeutralButton等按钮阻止关闭功能
*/
public class AlertDialogHelper {
private static final String LogTag = "AlertDialogHelper";
// 获取Dialog的mShowing成员
static public Field get_mShowing_field(DialogInterface dialog) {
Field fieldmShowing = null;
try {
//Log.e(LogTag, "名称:" + dialog.getClass().getSuperclass().getSimpleName() + " " + dialog.getClass().getSuperclass().getSuperclass().getSimpleName());
//通过反射获取Dialog中的私有属性mShowing
if (dialog.getClass().getSuperclass().getSimpleName().compareTo("Dialog") == 0) {
fieldmShowing = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
} else if (dialog.getClass().getSuperclass().getSuperclass().getSimpleName().compareTo("Dialog") == 0) {
fieldmShowing = dialog.getClass().getSuperclass().getSuperclass().getDeclaredField("mShowing");
}
else
{
Log.e(LogTag, "Dialog基类找不到");
}
} catch (Exception ex) {
ex.printStackTrace();
}
return fieldmShowing;
}
// 设置mShowing=false忽略关闭请求
static public void ignoreClose(DialogInterface dialog) {
Field fieldmShowing = get_mShowing_field(dialog);
if (null != fieldmShowing) {
fieldmShowing.setAccessible(true); //设置该属性可以访问
try {
fieldmShowing.set(dialog, false); // 阻止关闭请求
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
// 恢复关闭请求
static public void recoverClose(DialogInterface dialog) {
Field fieldmShowing = get_mShowing_field(dialog);
if (null != fieldmShowing) {
fieldmShowing.setAccessible(true); //设置该属性可以访问
try {
fieldmShowing.set(dialog, true); // 恢复关闭请求
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
使用方法:
View layoutEdit = View.inflate(getContext(), R.layout.multi_line_edit, null);
final EditText editLease = layoutEdit.findViewById(R.id.multiLineEdit);
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("输入XXXXXX");
builder.setView(layoutEdit);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialogHelper.recoverClose(dialog);
String strCode = editLease.getText().toString().trim();
if (strCode.isEmpty()) {
AlertDialogHelper.ignoreClose(dialog);
return;
}
}
}
);
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialogHelper.recoverClose(dialog);
}
}
);
//AlertDialog dlg = builder.create();
//dlg.show();
AlertDialog dlg = builder.show();