安卓开发——问题:Activity使用Dialog样式导致点击空白处自动关闭

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28484355/article/details/79474761

项目中实现一个通话功能时,需要弹出一个类似Dialog样式的呼叫或被呼叫窗口,这个窗口实际是一个Activity,theme设置为Dialog样式,如下:


但实际运行中,就暴露一个问题,就是这个窗口具备了Dialog的特性,即:点击窗口外的透明区域时,窗口退出了,这个可不是我想要的。

解决:

一、API大于等于11时:

方法1:在这个Activity的theme中添加:

<item name="android:windowCloseOnTouchOutside">false</item>
即:


方法2:在代码中设置:

XXXXActivity.this.setFinishOnTouchOutside(false);
二、API小于11时,重写Activity的onTouchEvent函数,如下:

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN && isOutOfBounds(this, event)) {
        return true;
    }
    return super.onTouchEvent(event);
}

private boolean isOutOfBounds(Activity 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 = context.getWindow().getDecorView();
    return (x < -slop) || (y < -slop)|| (x > (decorView.getWidth() + slop))|| (y > (decorView.getHeight() + slop));
}







猜你喜欢

转载自blog.csdn.net/qq_28484355/article/details/79474761