我有下面的代码可以做到这一点:我有一个带有背景的ImageView对象和一个表示图形的位图。图形是我绘制它的矩形。当我触摸ImageView对象时,如果我触摸图形矩形中的某个位置,我将“拿起”图形并在手指移动时移动它,当我抬起手指时将其放下。如果我触摸图形矩形以外的任何地方,我应该什么都不做——完全忽略触摸。我的代码如下:
protected int lastx, lasty;
protected MyImageView iv;
...
public boolean onTouch(View v, MotionEvent event) {
switch(event.getActionMasked())
{
case MotionEvent.ACTION_DOWN:
lastx = (int)event.getX();
lasty = (int)event.getY();
if(!iv.inFigure((int)lastx, (int)lasty))
{
return false;
}
else
{
return true;
}
case MotionEvent.ACTION_MOVE:
int x = (int) event.getX();
int y = (int) event.getY();
iv.move(x - lastx, y - lasty);
lastx = x;
lasty = y;
return true;
default:
{
int x = (int) event.getX();
int y = (int) event.getY();
iv.move(x - lastx, y - lasty);
lastx = x;
lasty = y;
return true;
}
}
}
问题是,无论我在哪里触摸屏幕图形都开始移动,而不仅仅是当我触摸它的矩形时。
iv.inFigure(x,y)工作正常,证据是当我添加这个布尔变量时,这段代码工作正常:
protected int lastx, lasty;
protected MyImageView iv;
protected boolean startMoving = false;
...
public boolean onTouch(View v, MotionEvent event) {
switch(event.getActionMasked())
{
case MotionEvent.ACTION_DOWN:
lastx = (int)event.getX();
lasty = (int)event.getY();
if(!iv.inFigure((int)lastx, (int)lasty))
{
startMoving = false;
return false;
}
else
{
startMoving = true;
return true;
}
case MotionEvent.ACTION_MOVE:
if(startMoving)
{
int x = (int) event.getX();
int y = (int) event.getY();
iv.move(x - lastx, y - lasty);
lastx = x;
lasty = y;
}
return true;
default:
{
if(startMoving)
{
int x = (int) event.getX();
int y = (int) event.getY();
iv.move(x - lastx, y - lasty);
lastx = x;
lasty = y;
}
return true;
}
}
}
据我所知,第一个代码应该在不添加额外标志的情况下工作,因为当ACTION_DOWN返回false时,ACTION_MOVE将被忽略,直到我们再次检测到ACTION_DDOWN并返回true。所以,当我触摸屏幕的某个地方,在图中会返回错误时,我应该忽略从触摸开始的任何移动,但我的图形仍然会移动。使用startMoving变量和其他检查,一切都正常。但我不想使用这个变量,我想知道为什么我的代码没有它就不能工作。问题是什么?