Search code examples
androidviewviewgroup

Views in ViewGroup


I ve the following scenario. I ve a viewgroup and two views (one draws a rectshape, an ovalshape the other). The viewgroup and the two views implements the OnTouchListener interface. But when a touch on a view, both the Viewgroup.onTouch(..) and the RectView.onTouch() and the OvalView.onTouch() are called. My question is.. if I want to know wich view has been touched what i need to do? Could please provide me some information or example?

Thanks in advance,


Solution

  • Well, let's take a look at OnTouchListener.

    You see there onTouch(View, MotionEvent) returns a boolean value if it has consumed the event. So with that in mind, you'll probably want to do some math and see if your RectView or OvalView contains the touch event (use MotionEvent to get the X,Y coordinate). If it does contain it, return true to signify that view has consumed the touch event.

    Now I'm not exactly clear on which order each onTouch() is called, but I assume it calls the child views first and, if that child view returned false, it will go on calling the rest of the onTouch() methods.

    If it's important to differentiate if RectView or OvalView was touched (e.g., both could theoretically be touched simultaneously), you'll have to do some sort of added work to see which one you prefer to accept (maybe one is drawn on top of the other).