[英]How to handle short and long button clicks
我如何處理短按和長按按鈕? 我需要對短按鈕單擊和長按鈕單擊上的特定操作進行一些特定操作。 我讀到了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>
要執行此操作,您可以使用按鈕的自定義渲染器。 每個平台都有自己的方式來處理當前未通過表單按鈕公開的長手勢。
在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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.