Android Dialog点击内容外围小部分区域没有消失
程序员文章站
2022-05-28 11:53:59
...
这两天做一个dialog,发现点击紧贴dialog内容的外围小部分区域时,dialog无法消失,但是,我明明已经设置了:
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
两个都赋值true,问题依旧。
后来看源码,发现是因为window中的一个函数的限制原因:
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();
final View decorView = getDecorView();
return (x < -slop) || (y < -slop)
|| (x > (decorView.getWidth()+slop))
|| (y > (decorView.getHeight()+slop));
}
需要重写onTouchEvent函数。
自定义dialog,继承自Dialog,完整代码:
public class BannerDialog extends Dialog {
public BannerDialog(@NonNull Context context) {
super(context);
}
public BannerDialog(@NonNull Context context, int themeResId) {
super(context, themeResId);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setCancelable(true);
setCanceledOnTouchOutside(true);
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
// return super.onTouchEvent(event);
Window window = getWindow();
if (null == window) {
return false;
}
final View decorView = window.getDecorView();
if (isShowing() && shouldCloseOnTtouch(event, decorView)) {
cancel();
return true;
}
return false;
}
private boolean shouldCloseOnTtouch(MotionEvent event, View decorView) {
final int x = (int) event.getX();
final int y = (int) event.getY();
return x <= 0 || y <= 0 || x > decorView.getWidth() || y > decorView.getHeight();
}
}
上一篇: ViewPager中切换界面Fragment被销毁
下一篇: 神经网络梯度消失、梯度爆炸