如何在C#(Xamarin)中使用setOnTouchListener? [英] How to use setOnTouchListener in C# (Xamarin)?

查看:158
本文介绍了如何在C#(Xamarin)中使用setOnTouchListener?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能给我一个用C#编写的setOnTouchListener示例吗?

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";
        }
    });

推荐答案

您要么a.使用 Touch 事件:

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;
};

或者您可以显式实现 IOnTouchListener 接口(C#没有匿名类).请注意,在实现Java接口时,还需要从 Java.Lang.Object 继承,因为我们需要故事中Java端的句柄(当使用触摸事件).

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;
    }
}

然后将其设置为:

button1.SetOnTouchListener(new MyTouchListener());

请注意,使用后一种方法还需要您处理对要在 OnTouchListener 类中修改的对象的引用的传递,而C#事件不需要这样做.

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.

附带说明一下,如果您使用 Touch 事件或任何其他事件,请记住要成为好公民,并在不想再接收该事件时取消该事件.最坏的情况是,如果您忘记取消挂接事件,则会泄漏内存,因为无法清理实例.

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;

记住要摘下它:

button1.Touch -= OnButtonTouched;

这篇关于如何在C#(Xamarin)中使用setOnTouchListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆