我如何处理短按和长按按钮?我需要对短按钮单击和长按钮单击上的特定操作进行一些特定操作。 我读到了Gesture Listener,并尝试将其实现到Android MainActivity.cs文件(MainActivity类)中。但是在应用程序运行时我有异常。
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Test.Page">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<ListView x:Name="MyButton" Grid.Row="0" />
<ScrollView Orientation="Horizontal" Grid.Row="1">
<Label x:Name="MyLabel" HorizontalOptions="Center">...</Label>
</ScrollView>
</Grid>
</ContentPage>
答案 0 :(得分:3)
要执行此操作,您可以使用按钮的自定义渲染器。每个平台都有自己的方式来处理当前没有通过表单按钮公开的长手势。
在Android上:
[assembly: Xamarin.Forms.ExportRenderer (typeof (MyButton), typeof (MyButtonRenderer))]
namespace MyApp.Android
{
public class MyButtonRenderer : ButtonRenderer
{
protected override void OnElementChanged (ElementChangedEventArgs<global::Xamarin.Forms.Button> e)
{
base.OnElementChanged (e);
if (e.OldElement == null) {
var nativeButton = Control;
nativeButton.LongClick += delegate {
//Do something
};
}
}
}
}
在iOS上:
[assembly:ExportRenderer (typeof(ButtonWithLongPressGesture), typeof(LongPressGestureRecognizerButtonRenderer))]
namespace SampleApp.iOS
{
public class LongPressGestureRecognizerButtonRenderer : ButtonRenderer
{
ButtonWithLongPressGesture view;
public ButtonPressGestureRecognizerImageRenderer ()
{
this.AddGestureRecognizer (new UILongPressGestureRecognizer ((longPress) => {
if (longPress.State == UIGestureRecognizerState.Began) {
view.HandleLongPress(view, new EventArgs());
}
}));
}
protected override void OnElementChanged (ElementChangedEventArgs<Button> e)
{
base.OnElementChanged (e);
if (e.NewElement != null)
view = e.NewElement as ButtonWithLongPressGesture;
}
}
}