如何检测活动边界外的触摸事件

时间:2014-01-17 17:13:27

标签: java android android-layout view android-activity

  

我有活动A超过活动B.活动A没有填满整个屏幕。(虽然它不是对话活动)我想在活动A边界外检测到触摸事件时关闭活动A.如何检测活动边界外的触摸事件?

@覆盖

public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
        Toast.makeText(getApplicationContext(), "Hi", 3000).show();

        return true;
    }

    return false;
}
  

此代码不起作用,因为它仅适用于对话活动。请帮助..提前谢谢:)

1 个答案:

答案 0 :(得分:1)

我不知道这是否有效,所以请测试它:) 但它应该很简单:

在actvity A的onCreate()

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    //set us to non-modal, so that others can receive the outside touch events.
    getWindow().setFlags(LayoutParams.FLAG_NOT_TOUCH_MODAL, LayoutParams.FLAG_NOT_TOUCH_MODAL);

    //and watch for outside touch events too
    getWindow().setFlags(LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);

    //be sure to set the content view after setting those flags!!
    setContentView(R.layout.my_view);
}

现在你接收正常`onTouch()'的触摸事件 只检查它是否在外面(得到x和y并检查窗口的位置)