Android MotionEvent for Touch 被按住?

标签 android

我刚刚开始使用 Android 进行开发,我正在尝试制作一款非常基本的游戏,您必须在屏幕底部移动 bat 并接住元素,同时避免炸弹。

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

目前,我可以让 bat 在用户触摸屏幕时移动几个像素,但我无法让它继续移动,直到用户将手指从屏幕上移开。

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

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;
    }

如有任何帮助,我们将不胜感激! :)

最佳答案

我认为这可能行得通:

boolean actionUpFlag = false;


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

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

这是您要找的吗?

关于Android MotionEvent for Touch 被按住?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5133830/

相关文章:

java - 使用适用于 Android 的 Quizlet API

Android XML : android:elevation vs. 应用程序:海拔

android - onItemCheckedStateChanged() 在自定义 ExpandableListView 上只调用一次

安卓应用SSL解密

android - 将 Url 转换为 Uri

java - 如何从firebase数据库中的内部节点读取值?

android - 位置管理器显示为空

安卓 SQLite : attempt to re-open an already-closed object

Android - 如何打开免提电话和最大通话音量

android - firebase 如何自动发送推送通知