ale*_*zyk 6 c# xamarin.android xamarin xamarin.forms
如何在 Xamarin.Forms 应用程序中拦截应用程序级别的点击/点击事件?
我尝试在 MainPage 上使用类似的东西
<Grid.GestureRecognizers>
<TapGestureRecognizer Command="{Binding TappedCommand}" Tapped="TapGestureRecognizer_OnTapped"></TapGestureRecognizer>
</Grid.GestureRecognizers>
Run Code Online (Sandbox Code Playgroud)
但它只有在我点击空白区域时才有效,触摸按钮不会触发事件。
此外,我经常通过更改 MainPage 进行导航,因此即使它有效,我也必须添加此类识别器。
我想在我的应用程序中全局处理任何触摸/点击/点击事件,是否可以在 Xamarin.Forms 中?
这可以在特定于平台的应用程序中轻松设置,然后使用Xamarin.Forms依赖服务订阅/取消订阅事件。
您在这些事件中捕获的内容取决于您的需要,在本示例中,我只是捕获和事件化 x/y 值。
public class TouchEventArgs<T> : EventArgs
{
public T EventData { get; private set; }
public TouchEventArgs(T EventData)
{
this.EventData = EventData;
}
}
public interface IGlobalTouch
{
void Subscribe(EventHandler handler);
void Unsubscribe(EventHandler handler);
}
Run Code Online (Sandbox Code Playgroud)
MainActivity您的Xamarin.Android应用程序中:public EventHandler globalTouchHandler;
public override bool DispatchTouchEvent(MotionEvent ev)
{
globalTouchHandler?.Invoke(null, new TouchEventArgs<Point>(new Point(ev.GetX(), ev.GetY())));
return base.DispatchTouchEvent(ev);
}
Run Code Online (Sandbox Code Playgroud)
public class GlobalTouch : IGlobalTouch
{
public GlobalTouch() {}
public void Subscribe(EventHandler handler)
{
(Forms.Context as MainActivity).globalTouchHandler += handler;
}
public void Unsubscribe(EventHandler handler)
{
(Forms.Context as MainActivity).globalTouchHandler -= handler;
}
}
Run Code Online (Sandbox Code Playgroud)
DependencyService.Get<IGlobalTouch>().Subscribe((sender, e) =>
{
var point = (e as TouchEventArgs<Point>).EventData;
System.Diagnostics.Debug.WriteLine($"{point.X}:{point.Y}");
});
Run Code Online (Sandbox Code Playgroud)
注意:您应该分配一个委托,以便取消订阅...
307.628997802734:365.563842773438
309.280151367188:365.197265625
311.883605957031:365.390991210938
312.694641113281:380.148590087891
308.030578613281:387.823364257813
291.513244628906:396.339416503906
286.220489501953:396.339416503906
282.100006103516:396.339416503906
Run Code Online (Sandbox Code Playgroud)
相同的技术可用于 iOS,有TouchesBegan, TouchesEnded,TouchesMoved并且TouchesCancelled您可以根据需要附加....
| 归档时间: |
|
| 查看次数: |
3494 次 |
| 最近记录: |