2012-08-09 108 views
0

我试图找到协调是一个用户只在imageview内触摸。查找图像视图内的坐标?

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

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的内此代码的工作。

enter image description here

回答

2

你的问题是,你return false在onTouch事件的结束。

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

返回trueonTouchEvent,只要手指保持在屏幕上,您将继续收到一连串的事件,并在释放时发出最终事件。

+0

非常感谢!这么简单,但你为我节省了很多时间。 – user1472757 2012-08-09 22:52:05