add touch event listener to android canvas

2019-09-08 08:40发布

问题:

I have a canvas object (c) , and I need to add a touch event listener so that whenever the canvas is touched, I can call a function. I haven't been able to find how to add it on so far, Here's what I have:

c.setOnTouchListener(new onTouchListener(){onTouchEvent()});

and then the onTouchEvent method:

public boolean onTouchEvent(MotionEvent e){
    addBubble();
    return false;
}

new to both java and android development, thanks for any help!

If i'm not meant to add a touch listener to a canvas, then how should I achieve this?

回答1:

Canvases don't get touch events. Canvases aren't on screen elements, they're generic drawable areas, sort of like HDC in Win32. They don't even need to draw to the screen, they can draw to a bitmap in memory. Views are the on screen elements, and they have the touch listeners. You would need to add the listener to the view, not to a canvas.



回答2:

You could create a custom View implementation. Whatever you do with the Canvas, implement that in onDraw(), which receives a Canvas as a parameter. Then add your view to a layout and give it whatever listeners you want.