猿问

按下画布时如何调用方法

我正在开发一款带有车辆的游戏,我想在按下画布时移动这辆车,就像这样,但这不起作用。


public boolean onTouch(View v, MotionEvent event) {


    if (event.getX() > 0 && event.getX() < 150 && event.getY() > 550 && event.getY() < 700) {


           do{


              System.out.println("Hallo");


              }while (canvas.isPressed());


        return false;

但我只是得到这个输出:


D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN

I/System.out: Hallo

任何想法?


侃侃无极
浏览 100回答 2
2回答

呼如林

设置一个全局布尔值以了解何时MotionEvent.ACTION_DOWN收到事件。&nbsp;&nbsp;&nbsp;mUserTouched&nbsp;=&nbsp;true;&nbsp;//&nbsp;Set&nbsp;to&nbsp;true&nbsp;when&nbsp;MotionEvent.ACTION_DOWN &nbsp;&nbsp;&nbsp;mUserTouched&nbsp;=&nbsp;false;&nbsp;//&nbsp;set&nbsp;to&nbsp;false&nbsp;when&nbsp;MotionEvent.ACTION_UP&nbsp;is&nbsp;received然后,您可能需要使用一个Timer或其他一些循环程序,每当收到 MotionEvent.ACTION_DOWN 时,该循环程序就会首先启动。并让它根据某个时间间隔触发呼叫invalidate()。invalidate()将导致View.onDraw()被调用,以便您可以重新绘制汽车的位置。当接收到 MotionEvent.ACTION_UP 时,取消TimermUserTouched = false'如果有界限,那么每当MotionEvent发生在界限之外时,您还需要进行设置。

红糖糍粑

可以onTouch这样完成onTouchEvent:&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public boolean onTouchEvent(MotionEvent motionEvent) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Player has touched the screen&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case MotionEvent.ACTION_DOWN:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Hallo");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Player has removed finger from screen&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case MotionEvent.ACTION_UP:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答