我正在尝试使用以下代码在Android自定义视图中实现基本虚拟操纵杆。 p>
this.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent e) {
switch(e.getAction()){
case(MotionEvent.ACTION_DOWN):
moving = true;
joystickVisibility = true;
joystickCoordinates[0] = (int) e.getX() - imageJoystick.getWidth() / 2;
joystickCoordinates[1] = (int) e.getY() - imageJoystick.getHeight() / 2;
joystickBaseCoordinates[0] = (int) e.getX() - imageJoystickBase.getWidth() / 2;
joystickBaseCoordinates[1] = (int) e.getY() - imageJoystickBase.getHeight() / 2;
break;
case(MotionEvent.ACTION_MOVE):
joystickCoordinates[0] = (int) e.getX() - imageJoystick.getWidth() / 2;
joystickCoordinates[1] = (int) e.getY() - imageJoystick.getHeight() / 2;
if (joystickCoordinates[0] > joystickBaseCoordinates[0] + 50)
joystickCoordinates[0] = joystickBaseCoordinates[0] + 50;
if (joystickCoordinates[0] < joystickBaseCoordinates[0] - 50)
joystickCoordinates[0] = joystickBaseCoordinates[0] - 50;
if (joystickCoordinates[1] > joystickBaseCoordinates[1] + 50)
joystickCoordinates[1] = joystickBaseCoordinates[1] + 50;
if (joystickCoordinates[1] < joystickBaseCoordinates[1] - 50)
joystickCoordinates[1] = joystickBaseCoordinates[1] - 50;
break;
case(MotionEvent.ACTION_UP):
moving = false;
joystickVisibility = false;
break;
}
move();
postInvalidate();
return true;
}
});
除非操纵杆朝一个方向但未被移动,否则它正在工作。 在触摸屏幕时,我找不到任何有效的事件。