C# – How to use setOnTouchListener in C# (Xamarin)

androidc++xamarin

Can you give me an example of setOnTouchListener in C#?

I tried like this but I bring some errors.

Button1.setOnTouchListener(new View.OnTouchListener()
    {
        public boolean onTouch(View arg0, MotionEvent arg1)
        {
            x.Text = "1";
        }
    });

Best Solution

You either a. use the Touch event:

button1.Touch += (s, e) =>
{
    var handled = false;
    if (e.Event.Action == MotionEventActions.Down)
    {
        // do stuff
        handled = true;
    }
    else if (e.Event.Action == MotionEventActions.Up)
    {
        // do other stuff
        handled = true;
    }

    e.Handled = handled;
};

Or you can explicitly implement the IOnTouchListener interface (C# does not have anonymous classes). Note that when implementing Java interfaces, you also need to inherit from Java.Lang.Object as we need a handle to the Java side of the story (this is obviously not needed when we use the Touch event).

public class MyTouchListener 
    : Java.Lang.Object
    , View.IOnTouchListener
{
    public bool OnTouch(View v, MotionEvent e)
    {
        if (e.Action == MotionEventActions.Down)
        {
            // do stuff
            return true;
        }
        if (e.Action == MotionEventActions.Up)
        {
            // do other stuff
            return true;
        }

        return false;
    }
}

Then set it with:

button1.SetOnTouchListener(new MyTouchListener());

Note using the latter approach also needs you to handle passing of references to objects that you want to modify in your OnTouchListener class, this is not needed with the C# Event.

EDIT: As a side note, if you use the Touch event or any other event, please remember to be a good citizen and unhook the event when you are not interested in receiving it anymore. Worst case, if you forget to unhook the event, you will leak memory because the instance cannot be cleaned up.

So in the first example, don't use a anonymous method:

button1.Touch += OnButtonTouched;

And remember to unhook it:

button1.Touch -= OnButtonTouched;