Detecting touch gestures using OnTouchListener

Detecting touch gestures? You will be doing this often in Android application development. In this tutorial I’ll show you how to use OnTouchListener to detect touch events on ImageView and use them to recognize appropriate touch gesture and apply different transformations.

We will code simple android application in Kotlin which will give users ability to open image from gallery and to make it more fun by placing different props mustaches, santa’s hat and glasses on characters in image.

As you can see in example animation, our little application will support three different touch gestures: drag, rotate and zoom. Those gestures will enable precise placing of props to image. We will use OnTouchListener to gather data from touch events, interpret them so we can differentiate between those three gestures and apply appropriate transformations to our images (ImageViews).

A “touch gesture” occurs when a user places one or more fingers on the touch screen, and your application interprets that pattern of touches as a particular gesture.

Layout Setup

Our activity layout will be simple. RelativeLayout with FrameLayout containing four ImageViews followed by Floating Action Button for opening image from our phone gallery. Most important thing is using FrameLayout as parent for your ImageViews because it will provide consistency when draging, zooming and rotating images around. I have tried few different layouts but FrameLayout is only one I found to work well in this situation. Top three ImageViews will contain prop images and in fourth ImageView we will place image from our gallery to play with.

OnTouchListener

This is place where all our magic is happening, detecting touch events. Create new Kotlin file for our OnTouchListener which I will name VirtuoozaTouch, yes I know it is original, but name isn’t important here you can name it however you want.

MainActivity

Now when we have our OnTouchListener we can add it to our ImageViews which will contain props in our MainActivity. In our init() function we will setup layout parameters for every of our prop ImageViews and set OnTouchListener to our VirtuoozaTouch listener. Layout parameters include height, width and margins of ImageViews inside FrameLayout. We have to call init() function inside onCreate() in our MainActivity. openImage() function will allow us to open gallery and pick image from our device.