简体   繁体   English

如何处理短按和长按按钮

[英]How to handle short and long button clicks

How i can handle short and long button clicks? 我如何处理短按和长按按钮? I need some specific action on short button click and specific action on long button click. 我需要对短按钮单击和长按钮单击上的特定操作进行一些特定操作。 I read about Gesture Listener and try to implement it into Android MainActivity.cs file(MainActivity class). 我读到了Gesture Listener,并尝试将其实现到Android MainActivity.cs文件(MainActivity类)中。 But i have exception when application runs. 但是在应用程序运行时我有异常。

<?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>

To do this you could use a custom renderer for the button. 要执行此操作,您可以使用按钮的自定义渲染器。 Each platform would have its own way of handling a long gesture which is not currently exposed through the forms button. 每个平台都有自己的方式来处理当前未通过表单按钮公开的长手势。

On Android: 在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
                        };
                    }
                }
    }
}

On iOS: 在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM