如何在Dialog之外触摸时捕获事件

时间:2014-10-31 10:21:31

标签: android

我的应用程序有dialog。当用户catch event clicks outside时,我想dialog。我该怎么做?

这是我的代码,但它没有运行。

@Override
public boolean onTouchEvent(MotionEvent event) {
    float x = event.getX();
    float y = event.getY();`enter code here`
    int xmargin = (ViewUtils.getScreenWidth() - Constants.PRODUCT_DIALOG_WIDTH) / 2;
    int ymargin = (ViewUtils.getScreenHeight() - Constants.PRODUCT_DIALOG_HEIGHT) / 2;

    if (
            x < xmargin|| 
            x > ViewUtils.getScreenWidth() - xmargin ||
            y < ymargin|| 
            y > ViewUtils.getScreenHeight() - ymargin
        ) {
            finish();
            return true;
    }
    return super.onTouchEvent(event);
}

谢谢大家!

1 个答案:

答案 0 :(得分:0)

当您在对话框外触摸时,您可以查看此代码 -

Window window = dialog.getWindow();
        window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
        window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        dialog.show();

希望这有帮助。