简体   繁体   English

Android:如何将OnTouchListener添加到Canvas?

[英]Android: How to add OnTouchListener to Canvas?

I have a class with animation on the canvas. 我在画布上有一个动画课。 I need to handle touching, but OnTouchListener doesn't work. 我需要处理触摸,但是OnTouchListener不起作用。 I tried to put a listener to main activity, but it didn't work anyway. 我尝试将侦听器置于主要活动中,但是无论如何它还是没有用。

public class Animation extends View implements View.OnTouchListener{

    private Paint paint;
    private Snake snake;

    public Animation(Context context) {
        super(context);
        snake = new Snake(10, 10, 1, 0, 1, 50);
        paint = new Paint();
        paint.setColor(Color.BLACK);
    }

    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        snake.move(canvas);
        invalidate();
    }

    public boolean onTouch(View v, MotionEvent event) {
        System.out.println("asfaf");
        float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                System.out.println(x + ' ' + y);
                break;
            case MotionEvent.ACTION_MOVE:
                System.out.println(x + ' ' + y);
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                System.out.println(x + ' ' + y);
                break;
        }
        return true;
    }

}

Replace your onTouch() method with onTouchEvent() . 将您的onTouch()方法替换为onTouchEvent()

@Override
public boolean onTouchEvent(MotionEvent event) {
    System.out.println("asfaf");
    float x = event.getX();
    float y = event.getY();

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            System.out.println(x + ' ' + y);
            break;
        case MotionEvent.ACTION_MOVE:
            System.out.println(x + ' ' + y);
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_CANCEL:
            System.out.println(x + ' ' + y);
            break;
    }
    return true;
}

and remove implements View.OnTouchListener . 并删除implements View.OnTouchListener

删除implements View.OnTouchListener从你的类,并把一个@Override在你onTouchEvent()方法。

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

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