简体   繁体   English

视图类中的Android onTouchEvent

[英]Android onTouchEvent in a view class

I've tried debugging with messages and stuff but the only value i get from event.getAction() is 0 ... which i believe is ACTION_DOWN why dont i detect ACTION_MOVE or ACTION_UP?? 我已经尝试过调试消息和东西但是我从event.getAction()得到的唯一值是0 ...我相信是ACTION_DOWN为什么我不检测ACTION_MOVE或ACTION_UP?

package com.andrewxd.test01;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;

public class Game extends View {

    private Bitmap enemy;
    private Enemy enemyN;
    private Paint paint;
    private float x,y;

    public Game(Context context) {
        super(context);
        enemy = BitmapFactory.decodeResource(getResources(), R.drawable.enemy);
        enemy = Bitmap.createScaledBitmap(enemy, 300 , 300, false);
        enemyN = new Enemy(10, 10, enemy);
        paint = new Paint();
        x = 0;
        y = 0;
    }

    @Override
    protected void onDraw(Canvas canvas){
        canvas.drawRect(x, y, 50, 50, paint);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event){
        super.onTouchEvent(event);
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            x = event.getX();
            y = event.getY();
            invalidate();
        } else if(event.getAction() == MotionEvent.ACTION_MOVE){
            x = event.getX();
            y = event.getY();
            invalidate();
        }
        return false;
    }
}

Am I doing something wrong? 难道我做错了什么? or is this supposed to work like this? 或者这应该是这样的? And if this is supposed to be like this where do i detect touch movement 如果这应该像这样我在哪里检测触摸运动

It's because you're returning false at the end of the onTouchEvent. 这是因为你在onTouchEvent的末尾返回false When you return false , you are saying that your View can not handle any more touch events so the events will no longer be sent to the View . 如果您返回false ,则表示您的View无法再处理任何触摸事件,因此事件将不再发送到View If you want to receive MOVE and UP events, then you need to return true. 如果要接收MOVEUP事件,则需要返回true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM