重写 Dialog 的 onTouchEvent 方法即可。
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
//触摸外部弹窗
if (isOutOfBounds(getContext(), event)) {
// do somthing
}
return super.onTouchEvent(event);
}
// 点击位置是否在对话框外部区域
private boolean isOutOfBounds(Context context, MotionEvent event) {
final int x = (int) event.getX();
final int y = (int) event.getY();
final int slop = ViewConfiguration.get(context).getScaledWindowTouchSlop();
Window window = getWindow();
if (window == null) return true;
final View decorView = window.getDecorView();
return (x < -slop) || (y < -slop) || (x > (decorView.getWidth() + slop))
|| (y > (decorView.getHeight() + slop));
}