Activity 上的 OnTouchListener

OnTouchListener on Activity

目前我在按钮上有一个 OnTouchListener,它工作正常。代码如下:

    Button button1 =(Button) findViewById(R.id.btOk1);
    button1.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            //do some stuff here
            return false;
        }
    });

我希望在我的整个 Activity 上有一个 OnTouchListener,这样每当用户点击我的 Activity 的任何区域时我都会做一些事情。我的 activity 的根布局是 TableLayout。我该怎么做?

谢谢!

编辑:

我设法通过命名我的根布局并设置一个 onTouchListener 来使用,如下所示:

    View view = findViewById(R.id.mylayout);
    view.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            Log.d(TAG, "onTouch");
            if ((event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
                Log.d(TAG, "Obscured");
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    new AlertDialog.Builder(MyActivity.this)
                        .setTitle("Alert!")
                        .setMessage("Overlay detected!")
                        .setNeutralButton("Dismiss", null)
                        .show();
                }
                // Return true to prevent the button from processing the touch.
                return true;
            } else {
                Log.d(TAG, "Not obscured");
            }
            return false;
        }
    });

我现在几乎在布局上的任意位置单击时都会收到触摸事件。通过将 MotionEvent 的标志与 FLAG_WINDOW_IS_OBSCURED 进行比较,我还能够检测将触摸事件传递到我的 Activity 的叠加层,但前提是被触摸的区域实际上被遮盖了。此外,onTouchListener 似乎不会在触摸 UI 元素(例如 Buttons 和 EditText)时调用,而只会在空白 space.

上调用

有没有办法检测我的 Activity 的任何部分是否被遮挡,有没有办法让整个 Activity 有一个 onTouchListener() 而不是单独的 onTouchListener()对于每个 UI 个元素?

将 OnTouchListener 应用于活动的根布局。这将解决问题。

this.setOnClickListener(this);

它可能不适用于活动,但它确实适用于扩展 SurfaceView

的 类

创建一个具有宽度和高度的相对布局"fill_parent"。 然后在 activity 中为相对布局创建一个 onTouchListener。

RelativeLayout relativeLayout  =(RelativeLayout) findViewById(R.id.relativeLayout);
relativeLayout.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        //do some stuff here
        return false;
    }
});

如果你只是想知道触摸事件发生了,即没有触摸视图的信息,你可以覆盖Activity的dispatchTouchEvent。