gpt4 book ai didi

c# - 如何在 C# (Xamarin) 中使用 setOnTouchListener?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:33:11 27 4
gpt4 key购买 nike

你能给我一个 C# 中的 setOnTouchListener 的例子吗?

我这样试过,但我带来了一些错误。

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

最佳答案

你要么使用 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 接口(interface)(C# 没有匿名类)。请注意,在实现 Java 接口(interface)时,您还需要从 Java.Lang.Object 继承,因为我们需要一个 Java 方面的句柄(当我们使用 时显然不需要)触摸事件)。

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# Event 则不需要。

编辑:作为旁注,如果您使用 Touch 事件或任何其他事件,请记住做一个好公民,并在您不再有兴趣接收它时取消 Hook 该事件。最坏的情况是,如果您忘记取消 Hook 事件,您将泄漏内存,因为无法清理实例。

所以在第一个例子中,不要使用匿名方法:

button1.Touch += OnButtonTouched;

记得解开它:

button1.Touch -= OnButtonTouched;

关于c# - 如何在 C# (Xamarin) 中使用 setOnTouchListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25223661/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com