add touch event listener to android canvas

独自空忆成欢 提交于 2019-12-13 03:58:15

问题


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.



来源:https://stackoverflow.com/questions/17635688/add-touch-event-listener-to-android-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!