要实现Android AlertDialog不应该因为背景点击而消失,可以通过以下代码示例来解决:
public class CustomAlertDialog extends AlertDialog {
public CustomAlertDialog(Context context) {
super(context);
}
public CustomAlertDialog(Context context, int themeResId) {
super(context, themeResId);
}
protected CustomAlertDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
super(context, cancelable, cancelListener);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setCancelable(false); // 设置dialog不可取消
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
return false; // 不响应外部点击事件
}
return super.dispatchTouchEvent(event);
}
}
CustomAlertDialog dialog = new CustomAlertDialog(MainActivity.this);
dialog.setTitle("提示");
dialog.setMessage("这是一个自定义的AlertDialog");
dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 点击确定按钮的逻辑处理
}
});
dialog.show();
通过以上代码示例,即可实现Android AlertDialog不会因为背景点击而消失。在自定义的AlertDialog中,重写了dispatchTouchEvent方法,在用户点击AlertDialog外部时,不响应外部点击事件。