0

我试图找到用户仅在图像视图内触摸的坐标。

到目前为止,我已经通过以下代码设法做到了这一点:

    img = (ImageView) findViewById(R.id.image);
    img.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            x = (int) event.getX();
            y = (int) event.getY();
            int[] viewCoords = new int[2];
            img.getLocationOnScreen(viewCoords);
            int imageX = (int) (x - viewCoords[0]); // viewCoods[0] is the X coordinate
            int imageY = (int) (y - viewCoords[1]); // viewCoods[1] is the y coordinate
            text.setText("x:" +x +"y"+y);

            return false;
        }
    });

然而这是 onTouchListener 这意味着它只在每次触摸后找到坐标,我想做的是创建它,以便在用户在图像视图周围移动手指时不断找到坐标。我通过这段代码在整个屏幕上实现了这一点:

@Override
public boolean onTouchEvent(MotionEvent event) {
    x = (float)event.getX();
    y = (float)event.getY();
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
        case MotionEvent.ACTION_UP:
    }



    text.setText("x:"+ x +" y:" +y);

return false;
}

但是我不知道如何使此代码仅在 imageview 内工作。

在此处输入图像描述

4

1 回答 1

2

您的问题是您return false在 onTouch 事件结束时。

当 you 时return false,您是在告诉操作系统您不再对与此特定手势相关的任何事件感兴趣,因此它会停止通知您对未来活动的看法(例如 ACTION_MOVE 和 ACTION_UP)。

返回trueonTouchEvent只要手指按住屏幕,您将继续接收事件流,并在松开手指时收到最终事件。

于 2012-08-09T22:44:29.307 回答