我有一个使用 OnTouch 的画布绘图,但是由于某种原因,我无法让它正常工作。它第一次工作(第一次触摸运动)。但是,当用户移开手指时,OnTouch 不再运行,从而阻止用户移动字符项。
经过大量研究和各种不同的选择,我根本无法让它工作,并且这样做注意到第一次调用 ACTION_DOWN 然后调用 ACTION_UP。
下面你可以找到我的两段代码,第一段是实际的 onTouchEvent。第二块代码用于处理我绘制的画布(基于迷宫(5 x 5))中的用户权限。
另一个要考虑的问题是画布被重绘(无效),每次移动用户位置(这是一个正方形的)
@Override
public boolean onTouchEvent(MotionEvent event)
{
float touchX = event.getX();
float touchY = event.getY();
int currentX = maze.getCurrentX();
int currentY = maze.getCurrentY();
switch (event.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN:
if(Math.floor(touchX/totalCellWidth) == currentX && Math.floor(touchY/totalCellHeight) == currentY)
{
dragging = true;
return true;
}
break;
case MotionEvent.ACTION_UP:
dragging = false;
break;
case MotionEvent.ACTION_MOVE:
if(dragging)
{
int cellX = (int)Math.floor(touchX/totalCellWidth);
int cellY = (int)Math.floor(touchY/totalCellHeight);
if((cellX != currentX && cellY == currentY) || (cellY != currentY && cellX == currentX))
{
boolean moved = false;
switch(cellX-currentX)
{
case 1:
moved = maze.move(Maze.RIGHT);
break;
case -1:
moved = maze.move(Maze.LEFT);
}
switch(cellY-currentY)
{
case 1:
moved = maze.move(Maze.DOWN);
break;
case -1:
moved = maze.move(Maze.UP);
}
if(moved)
{
invalidate();
if(maze.isGameComplete())
{
showFinishDialog();
}
}
}
break;
}
}
return true;
}
迷宫位置处理程序代码:
public boolean move(int direction)
{
boolean moved = false;
if(direction == UP)
{
if(currentY != 0 && !horizontalLines[currentY-1][currentX])
{
currentY--;
moved = true;
}
}
if(direction == DOWN)
{
if(currentY != verticalLines[0].length-1 && !horizontalLines[currentY][currentX])
{
currentY++;
moved = true;
}
}
if(direction == RIGHT)
{
if(currentX != horizontalLines[0].length-1 && !verticalLines[currentY][currentX])
{
currentX++;
moved = true;
}
}
if(direction == LEFT)
{
if(currentX != 0 && !verticalLines[currentY][currentX-1])
{
currentX--;
moved = true;
}
}
if(moved)
{
if(currentX == finalX && currentY == finalY)
{
gameComplete = true;
}
}
return moved;
}