Android MotionEvent for Touch被按下了吗?

时间:2011-02-27 14:49:23

标签: android

我刚刚开始在Android上开发,我正在尝试制作一个非常基本的游戏,你必须在屏幕底部移动一只蝙蝠并在避开炸弹的同时抓住物品。

我遇到的问题是,当您将手指放在屏幕的左侧或右侧时,我希望球棒沿着屏幕底部移动。

目前,当用户触摸屏幕时,我可以让蝙蝠移动几个像素,但是在用户将手指从屏幕上移开之前我无法继续移动。

到目前为止,这是我的(非常)基本代码:

package com.mattdrewery.supercatch;

import android.view.View;
import android.view.MotionEvent;
import android.content.Context;
import android.graphics.Canvas;

public class GameView extends View 
{
    private Catcher catcher;

    public GameView(Context context)
    {
        super(context);
        setFocusable(true);

        // Create the catcher
        catcher = new Catcher(context, R.drawable.catcher, 240, 250);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        // Draw the catcher to the canvas
        canvas.drawBitmap(catcher.getImage(), catcher.getPosX(),  catcher.getPosY(), null);

        // Redraw the screen
        invalidate();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        // Get the action from the touch screen
        int eventAction = event.getAction();

        int X = (int) event.getX();
        int Y = (int) event.getY();

        // If the user presses on the screen....
        if (eventAction == MotionEvent.ACTION_DOWN)
        {
            catcher.moveLeft();
        }

        // Redraw the screen
        invalidate();

        return true;
    }
}

catcher.moveLeft()方法如下:

public void moveLeft()
    {
        posX -= 5;
    }

对此事的任何帮助将不胜感激! :)

3 个答案:

答案 0 :(得分:5)

我认为这可能会奏效:

boolean actionUpFlag = false;


if (eventAction == MotionEvent.ACTION_DOWN)
        {
            actionUpFlag = true;
        }
else if (eventAction == MotionEvent.ACTION_UP)
        {
             actionUpFlag = false;
        }

while (actionUpFlag)
{
     catcher.moveLeft();
}

这是你在找什么?

答案 1 :(得分:1)

ZoomControls使用ZoomButton,它可以完成你想要的任务。它使用postDelayed()并检查按钮是否仍被按下以重复onClick操作。看看源代码,看看它是如何工作的(我没有深入,我只是一个提示)。

答案 2 :(得分:0)

尝试为onTouchEvent返回false。如果事件被处理,它应该从docs返回True,否则返回false。我想这会对你有帮助。