Track Touch Events and Detecting Touch Gestures in a View or Activity

Animation in Android
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. There are correspondingly two phases to gesture detection.
  1. Gather data about touch events.
  2. Interpret the data to see if it meets the criteria for any of the gestures your app supports.

Let discuss these phases more precisely.

Gather data
When a user places one or more fingers on the screen, this triggers the callback onTouchEvent() on the View that received the touch events. For each sequence of touch events (position, pressure, size, addition of another finger, etc.) that is ultimately identified as a gesture, onTouchEvent() is fired several times.

The gesture starts when the user first touches the screen, continues as the system tracks the position of the user's finger(s), and ends by capturing the final event of the user's fingers leaving the screen. Throughout this interaction, the MotionEvent delivered to onTouchEvent() provides the details of every interaction. Your app can use the data provided by the MotionEvent to determine if a gesture it cares about happened.

Note: For a single view we have an alternative to onTouchEvent(). The setOnTouchListener() method can attach a View.OnTouchListener object to a view.

Note: Beware of creating a listener that returns false for the ACTION_DOWN event. If you do this, the listener will not be called for the subsequent ACTION_MOVE and ACTION_UP string of events. This is because ACTION_DOWN is the starting point for all touch events.

Interpret the data There are some common gestures that we can detect by GestureDetector class. Common gestures include onDown(), onLongPress(), onFling(), and so on. You can use GestureDetector in conjunction with the onTouchEvent() method described above.
But there are situations in which we interpret the gathered data manually for example we want to detect a custom gesture. The following practice shows an example which we interpret the data manually.

Example:
Here we continue our example discussed in Animation by Canvas and just add some variables and suitable methods but the example is completely presented here to make it more easy to read.
Create a new Android Studio project and select an Empty Activity template. In CViewN class we add some proper variables(objects) and override onTouchEvent() method that has pivotal roll here.


Edit the activity_main.xml like below.


The MainActivity class which is an activity can also override the onTouchEvent() method. It makes it possible to for example drag the complete view instance inside the activity or any function related to whole view instance inside this activity. The below code shows how we can drag whole view when move our finger on touch.


Now run the application. The result should be something like below.


Comments