On this multipart series of posts we are going to review how to extend controls using Gesture Recognizers. This post is going to focus on the Tap Gesture Recognizer and by the end we will be able to turn a static image into a “clickable” image button.
Let’s get started by giving you some general information…
What is a Gesture Recognizer?
Xamarin.Forms allows us to extend the way we interact with some visual elements by way of Gesture Recognizers.
A Gesture Recognizer is an object that listens for some specific external estimule (the gesture) and launches an action in response (the command or event handler we specify).
A Gesture is any physical action taken by the user on the device. That goes from tapping on the surface of the screen to shaking the device. For the purposes of this series and in terms of Xamarin a gesture can be one of the following: Tap, Pinch, Pan and Swipe.
- A Tap happens when the user touches the control or the screen on a single point. From now on I will use the terms tap and click interchangeably.
- A Pinch happens when the user puts two fingers on the control or screen and either moves them towards one and other or against each other. Normally used for dynamic zooming.
- A Pan is when the user moves one finger across the screen.
- A Swipe is when the user moves their finger across the control on a straight line, horizontally, vertically or diagonally
Most if not all of Xamarin Forms controls have a property called GestureRecognizers that defines a collection of objects. We can define multiple Gesture Recognizers on the same control and we can also have multiple instances of the same Gesture Recognizer.
So, about that clickable Image…
In order to make an image clickable we have to add a TapGestureRecognizer to it and define the code we will want to execute when clicking it. Here is an example in XAML:
Here is the code we will execute when we tap the Image:
And here is the final result:
Explaining the code
We are using the NumberOfTapsRequired property to define how many times the user has to tap the control before the Gesture Recognizer launches the event. The Tapped property is used to specify the event handler that will take the task of responding to the gesture. In this case the OnTapGestureRecognizerTapped method.
We can also specify a Command instead of an event handler but that’s for another time.
Here are a few funny things you can try and experiment with:
- You can add multiple TapGestureRecognizers to the same control, say one for double tap and another one for single tap:
In my experience, adding multiple TapGestureRecognizers to the same control can produce some unexpected and even unpleasant behaviors like having the wrong event handler to launch.
- You can add multiple events for the same number of taps
I hope you have found this helpful or at the very least interesting. Stay tuned for the next entry in the series and have a good day.