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?
Make use of XLabs.Forms nuget package, which make long press and other gesture in PCL code only. Use of XLabs.Forms package will reduce the need of custom rendering in individual platforms... Add XAML code in .xaml file and attached event handler in .xaml.cs file.. It is working fine in Android..
C# backend code:
You can do it cross platform way by attaching the below behavior, as long as it is
Xamarin.Forms.Button
or a sub-type of it.In the XAML UI:
XAML UI with Command Binding:
I recently came across this problem and found a useful post on the topic https://alexdunn.org/2017/12/27/xamarin-tip-xamarin-forms-long-press-effect/
This makes use of the
RoutingEffect
and goes through an example of how to create both iOS and Android implementation. The simplicity of this allows you to attach it to any view in your app without recreating code.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 ownImageWithLongPressGesture
class).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.
This solution is a hybrid of answer on xamarin forms forum and Touch and Gestures presentation by Telerik.
In order to get this to work properly on iOS, you need to use XLabs.Forms.XFormsAppiOS.Init(); in your AppDelegate.cs file just before the LoadApplication(new App()); statement.