本文共 3211 字,大约阅读时间需要 10 分钟。
Xamarin.Forms 中默认是不实现这两个功能的,这就需要你在 Renderer 中自己去实现,下面是关于如何在 Xamarin.Android 中实现这个功能的代码:
public interface IMyButtonController : IViewController{ void SendTouched(); void SendLongClicked(); void SendReleased();}
public class MyButton : Xamarin.Forms.Button, IMyButtonController{ public event EventHandler Touched; void IMyButtonController.SendTouched() { Touched?.Invoke(this, EventArgs.Empty); } public event EventHandler LongClicked; void IMyButtonController.SendLongClicked() { LongClicked?.Invoke(this, EventArgs.Empty); } public event EventHandler Released; void IMyButtonController.SendReleased() { Released?.Invoke(this, EventArgs.Empty); }}
在 Xamarin.Android 中的 Renderer:
[assembly: ExportRenderer(typeof(MyButton), typeof(MyButtonRenderer))]namespace ProjectNameSpace.Droid{ public class MyButtonRenderer : Xamarin.Forms.Platform.Android.ButtonRenderer { protected override void OnElementChanged(ElementChangedEventArgse) { base.OnElementChanged(e); if (e.NewElement != null) { if (Control != null) { Control.SetOnTouchListener(ButtonTouchListener.Instance.Value); Control.LongClickable = true; Control.SetOnLongClickListener(ButtonLongClickListener.Instance.Value); } } } protected override void Dispose(bool disposing) { if (disposing) { if (Control != null) { Control.SetOnTouchListener(null); Control.SetOnLongClickListener(null); } } base.Dispose(disposing); } private class ButtonTouchListener : Java.Lang.Object, Android.Views.View.IOnTouchListener { public static readonly Lazy Instance = new Lazy (() => new ButtonTouchListener()); public bool OnTouch(Android.Views.View v, Android.Views.MotionEvent e) { var renderer = v.Tag as ButtonRenderer; if (renderer != null) { var buttonController = renderer.Element as IMyButtonController; if (e.Action == Android.Views.MotionEventActions.Down) { buttonController?.SendTouched(); } else if (e.Action == Android.Views.MotionEventActions.Up) { buttonController?.SendReleased(); } } return false; } } private class ButtonLongClickListener : Java.Lang.Object, Android.Views.View.IOnLongClickListener { public static readonly Lazy Instance = new Lazy (() => new ButtonLongClickListener()); public bool OnLongClick(Android.Views.View v) { var renderer = v.Tag as ButtonRenderer; ((IMyButtonController)renderer?.Element)?.SendLongClicked(); return true; } } }}
转载地址:http://kepgi.baihongyu.com/