Reader small image

You're reading from  Android Studio 4.2 Development Essentials - Kotlin Edition

Product typeBook
Published inAug 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781803231549
Edition1st Edition
Languages
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor's degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

34. Android Touch and Multi-touch Event Handling

Most Android based devices use a touch screen as the primary interface between user and device. The previous chapter introduced the mechanism by which a touch on the screen translates into an action within a running Android application. There is, however, much more to touch event handling than responding to a single finger tap on a view object. Most Android devices can, for example, detect more than one touch at a time. Nor are touches limited to a single point on the device display. Touches can, of course, be dynamic as the user slides one or more points of contact across the surface of the screen.

Touches can also be interpreted by an application as a gesture. Consider, for example, that a horizontal swipe is typically used to turn the page of an eBook, or how a pinching motion can be used to zoom in and out of an image displayed on the screen.

This chapter will explain the handling of touches that involve motion and explore...

34.1 Intercepting Touch Events

Touch events can be intercepted by a view object through the registration of an onTouchListener event listener and the implementation of the corresponding onTouch() callback method or lambda. The following code, for example, ensures that any touches on a ConstraintLayout view instance named myLayout result in a call to a lambda expression:

binding.myLayout.setOnTouchListener {v: View, m: MotionEvent ->

            // Perform tasks here

            true

}

Of course, the above code could also be implemented by using a function instead of a lambda as follows, though the lambda approach results in more compact and readable code:

binding.myLayout.setOnTouchListener(object : View.OnTouchListener {

    override fun onTouch(v: View, m: MotionEvent): Boolean {

      ...

34.2 The MotionEvent Object

The MotionEvent object passed through to the onTouch() callback method is the key to obtaining information about the event. Information contained within the object includes the location of the touch within the view and the type of action performed. The MotionEvent object is also the key to handling multiple touches.

34.3 Understanding Touch Actions

An important aspect of touch event handling involves being able to identify the type of action performed by the user. The type of action associated with an event can be obtained by making a call to the getActionMasked() method of the MotionEvent object which was passed through to the onTouch() callback method. When the first touch on a view occurs, the MotionEvent object will contain an action type of ACTION_DOWN together with the coordinates of the touch. When that touch is lifted from the screen, an ACTION_UP event is generated. Any motion of the touch between the ACTION_DOWN and ACTION_UP events will be represented by ACTION_MOVE events.

When more than one touch is performed simultaneously on a view, the touches are referred to as pointers. In a multi-touch scenario, pointers begin and end with event actions of type ACTION_POINTER_DOWN and ACTION_POINTER_UP respectively. In order to identify the index of the pointer that triggered the event, the...

34.4 Handling Multiple Touches

The chapter entitled “An Overview and Example of Android Event Handling” began exploring event handling within the narrow context of a single touch event. In practice, most Android devices possess the ability to respond to multiple consecutive touches (though it is important to note that the number of simultaneous touches that can be detected varies depending on the device).

As previously discussed, each touch in a multi-touch situation is considered by the Android framework to be a pointer. Each pointer, in turn, is referenced by an index value and assigned an ID. The current number of pointers can be obtained via a call to the getPointerCount() method of the current MotionEvent object. The ID for a pointer at a particular index in the list of current pointers may be obtained via a call to the MotionEvent getPointerId() method. For example, the following code excerpt obtains a count of pointers and the ID of the pointer at index 0:

...

34.5 An Example Multi-Touch Application

The example application created in the remainder of this chapter will track up to two touch gestures as they move across a layout view. As the events for each touch are triggered, the coordinates, index and ID for each touch will be displayed on the screen.

Select the Create New Project quick start option from the welcome screen and, within the resulting new project dialog, choose the Empty Activity template before clicking on the Next button.

Enter MotionEvent into the Name field and specify com.ebookfrenzy.motionevent as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language menu to Kotlin.

Adapt the project to use view binding as outlined in section 18.8 Migrating a Project to View Binding.

34.6 Designing the Activity User Interface

The user interface for the application’s sole activity is to consist of a ConstraintLayout view containing two TextView objects. Within the Project tool window, navigate to app -> res -> layout and double-click on the activity_main.xml layout resource file to load it into the Android Studio Layout Editor tool.

Select and delete the default “Hello World!” TextView widget and then, with autoconnect enabled, drag and drop a new TextView widget so that it is centered horizontally and positioned at the 16dp margin line on the top edge of the layout:

Figure 34-1

Drag a second TextView widget and position and constrain it so that it is distanced by a 32dp margin from the bottom of the first widget:

Figure 34-2

Using the Attributes tool window, change the IDs for the TextView widgets to textView1 and textView2 respectively. Change the text displayed on the widgets to read “Touch One Status&...

34.7 Implementing the Touch Event Listener

In order to receive touch event notifications it will be necessary to register a touch listener on the layout view within the onCreate() method of the MainActivity activity class. Select the MainActivity.kt tab from the Android Studio editor panel to display the source code. Within the onCreate() method, add code to register the touch listener and implement code which, in this case, is going to call a second method named handleTouch() to which is passed the MotionEvent object:

package com.ebookfrenzy.motionevent

 

import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

import android.view.MotionEvent

 

import com.ebookfrenzy.motionevent.databinding.ActivityMainBinding

 

class MainActivity : AppCompatActivity() {

 

    private lateinit var binding: ActivityMainBinding

 

    override fun onCreate(savedInstanceState: Bundle...

34.8 Running the Example Application

Compile and run the application and, once launched, experiment with single and multiple touches on the screen and note that the text views update to reflect the events as illustrated in Figure 34-3. When running on an emulator, multiple touches may be simulated by holding down the Ctrl (Cmd on macOS) key while clicking the mouse button (note that simulating multiple touches may not work if the emulator is running in a tool window):

Figure 34-3

34.9 Summary

Activities receive notifications of touch events by registering an onTouchListener event listener and implementing the onTouch() callback method which, in turn, is passed a MotionEvent object when called by the Android runtime. This object contains information about the touch such as the type of touch event, the coordinates of the touch and a count of the number of touches currently in contact with the view.

When multiple touches are involved, each point of contact is referred to as a pointer with each assigned an index and an ID. While the index of a touch can change from one event to another, the ID will remain unchanged until the touch ends.

This chapter has worked through the creation of an example Android application designed to display the coordinates and action type of up to two simultaneous touches on a device display.

Having covered touches in general, the next chapter (entitled “Detecting Common Gestures Using the Android Gesture Detector Class...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.2 Development Essentials - Kotlin Edition
Published in: Aug 2021Publisher: PacktISBN-13: 9781803231549
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor's degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth