Search code examples
xamarinxamarin.formsgesture

How to make long press gesture in Xamarin Forms?


Could you please let me know how can I recognize long press gesture in Xamarin Forms application?

A few days before I used TapGestureRecognizer

TapGestureRecognizer imageTap = new TapGestureRecognizer();
imageTap.Tapped += (sender, args) => this.OnClickImage;
image.GestureRecognizers.Add(imageTap);

But I don't know how to make long press gesture according to this thread from xamarin forum

It should looks something like this, but it does not work.

var dumpParam = new RelayGesture((g, x) => DisplayAlert("Title", "Hello message", "Cancel"));

book.Cover.SetValue(Gestures.InterestsProperty, new GestureCollection() {
    new GestureInterest
        {
            GestureType = GestureType.LongPress
            GestureCommand = // what should I set?
            GestureParameter = dumpParam
        }
 });

How to set my custom handler method?


Solution

  • Surfing the internet I found the solution. There are few steps which you should reproduce.

    1) Inherit the control you need the gestures on (i.e. if you want to add gesture to Xamarin.Forms.Image, create you own ImageWithLongPressGesture class).

    public class ImageWithLongPressGesture : Xamarin.Forms.Image
    {
        public EventHandler LongPressActivated;
    
        public void HandleLongPress(object sender, EventArgs e)
        {
            //Handle LongPressActivated Event
        }
    }
    

    2) Expose public events for the needed gestures.

    3) Create a Renderer for each platform.

    4) In the Renderer, handle the gestures and bubble them to your control.

    [assembly: ExportRenderer(typeof(ImageWithLongPressGesture), typeof(LongPressGestureRecognizerImageRenderer))]
    namespace App1.Droid.DroidRenderers
    {
        public class LongPressGestureRecognizerImageRenderer : ImageRenderer
        {
            ImageWithLongPressGesture view;
    
            public LongPressGestureRecognizerImageRenderer()
            {
                this.LongClick += (sender, args) => {
                    Toast.MakeText(this.Context, "Long press is activated.", ToastLength.Short).Show();
                };
            }
    
            protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
            {
                base.OnElementChanged(e);
    
                if(e.NewElement != null)
                {
                    view = e.NewElement as ImageWithLongPressGesture;
                }
            }
        }
    }
    

    This solution is a hybrid of answer on xamarin forms forum and Touch and Gestures presentation by Telerik.