2

Hopefully someone can help.

I'm trying to attach an OnTouchListener() to a view and it's children. In native android, this would be using the setOnTouchListener() method.

The Xamarin documentation seems to suggest using delegates for c#. But this seems not to work. Can anyone help with a basic demonstration on attaching an ontouch listener to a view and its children.

Below is the code I've tried.

    myView.Touch += (sender,e)=>
    {
        // Code to be executed
    }

And

    myView.Click += (sender,e)=>
    {
       // Code to be executed
    }
Phil B
  • 43
  • 6

1 Answers1

1

your samples work for me, however; in android if a child view handles the touch event then your parent will not. So by registering for the touch event like above, if you touch any child control, nothing happens because the child is handling the event, see Touch Listeners for Parent and Child Views. I see three ways to fix this:

  1. register the delegate for the parent and all children, (but that seems to be what you want to avoid...)
  2. in your parent view class, implement onInterceptTouchEvent, this means you need a custom view class. http://developer.android.com/reference/android/view/ViewGroup.html#onInterceptTouchEvent(android.view.MotionEvent)
  3. SetOnTouchListener still exists in M4A, you can use it on the parent and all children, same effect as option 1
Community
  • 1
  • 1
jcwmoore
  • 1,153
  • 8
  • 13
  • I am actually using a custom class, that extends Linear Layout, I don't suppose that this could be causing it to not work? Also, according to your explanation, If my view handles the onclick event, all children (of which, none handle it themselves) will use the same event, is this correct? – Phil B May 29 '12 at 09:47
  • no that would not cause it not to work, your children can use the same delegate if you register them all to that delegate/method. if you want your children to handle the touch event then they must be registered for it and they must call the delegate on the parent because by handling it at the child level your parent will not. that is how android works and not a side effect of M4A – jcwmoore May 31 '12 at 23:16