Reader small image

You're reading from  Android 9 Development Cookbook - Third Edition

Product typeBook
Published inOct 2018
Reading LevelIntermediate
PublisherPackt
ISBN-139781788991216
Edition3rd Edition
Languages
Tools
Right arrow
Author (1)
Rick Boyer
Rick Boyer
author image
Rick Boyer

Rick Boyer has been programming professionally for over 20 years. He has written apps on Windows, created websites, and coded for various mobile devices, including Windows CE, Windows Phone, and Android. Almost eight years ago, he took the plunge and started his own software consulting business, NightSky Development, focusing exclusively on Android development.
Read more about Rick Boyer

Right arrow

Chapter 9. Using the Touchscreen and Sensors

In this chapter, we will cover the following topics:

  • Listening for click and long-press events
  • Recognizing tap and other common gestures
  • Pinch-to-zoom with multi-touch gestures
  • Swipe-to-refresh
  • Listing available sensors—an introduction to the Android Sensor Framework
  • Reading sensor data—using Android Sensor Framework events
  • Reading device orientation

Introduction


These days, mobile devices are packed with sensors, often including a gyroscope, magnetic, gravity, pressure, and/or temperature sensors, not to mention the touchscreen. This provides many new and exciting options to interact with your user. Through the sensors, you can determine three-dimensional device location and how the device is being used, such as shaking, rotation, tilt, and so on. Even the touchscreen offers many new input methods from just the simple click to gestures and multi-touch.

We'll start this chapter by exploring touchscreen interactions, starting with a simple click and long-press, then move on to detecting common gestures using the SimpleOnGestureListener class. Next, we'll look at multi-touch using the pinch-to-zoom gesture with ScaleGestureDetector.

This book is meant to offer a quick guide to adding features and functionality to your own applications. As such, the focus is on the code required but it's highly recommended that you become familiar with the...

Listening for click and long-press events


Almost every application needs to recognize and respond to basic events such as clicks and long-presses. It's so basic, in most recipes we use the XML onClick attribute, but more advanced listeners require to be set up through code.

Android provides an Event Listener interface for receiving a single notification when certain actions occur, as shown in the following list:

  • onClick(): It's called when a View is pressed
  • onLongClick(): It's called when the View is long-pressed
  • onFocusChange(): It's called when the user navigates to or from the View
  • onKey(): It's called when a hardware key is pressed or released
  • onTouch(): It's called when a touch event occurs

This recipe will demonstrate responding to a click event, as well as a long-press event.

Getting ready

Create a new project in Android Studio and call it PressEventsUse the default Phone & Tablet options and select Empty Activity on the Add an Activity to Mobile dialog.

How to do it...

Setting up to receive...

Recognizing tap and other common gestures


Unlike the Event Listeners described in the previous recipe, gestures require a two-step process:

  1. Gather movement data
  2. Analyze the data to determine whether it matches a known gesture

Step 1 begins when the user touches the screen, which fires the onTouchEvent() callback with the movement data sent in a MotionEvent object. Fortunately, Android makes step 2, analyzing the data, easier with the GestureDetector class, which detects the following gestures:

  • onTouchEvent()
  • onDown()
  • onFling()
  • onLongPress()
  • onScroll()
  • onShowPress()
  • onDoubleTap()
  • onDoubleTapEvent()
  • onSingleTapConfirmed()

This recipe will demonstrate using GestureDetector.SimpleOnGestureListener to recognize the touch and double tap gestures.

Getting ready

Create a new project in Android Studio and call it CommonGestureDetector. Use the default Phone & Tablet options and select Empty Activity when prompted for the Activity Type.

How to do it...

We will be using the activity itself to detect gestures, so...

Pinch-to-zoom with multi-touch gestures


The previous recipe used SimpleOnGestureListener to provide detection of simple, one-finger gestures. In this recipe, we'll use the SimpleOnScaleGestureListener class to detect the common multi-touch gesture "pinch to zoom".

Here are two screenshots from the application we'll create in this recipe. The first shows the icon zoomed out:

This second screenshot shows the icon zoomed in:

Getting ready

Create a new project in Android Studio and call it MultiTouchZoom. Use the defaultPhone & Tablet options and select Empty Activity when prompted for the Activity Type.

How to do it...

To provide a visual indication of pinch-to-zoom, we'll use an ImageView with the application icon. Open activity_main.xml and follow these steps:

  1. Replace the existing TextView with the following ImageView:
<android.support.v7.widget.AppCompatImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher...

Swipe-to-Refresh


Pulling down a list to indicate a manual refresh is known as the Swipe-to-Refresh gesture. It's such a common feature that this functionality has been encapsulated in a single widget called SwipeRefreshLayout.

This recipe will add Swipe-to-Refresh functionality with a ListView. The following screenshot shows the refresh in action:

Getting ready

Create a new project in Android Studio and call it SwipeToRefreshUse the default Phone & Tablet options and select Empty Activity on the Add an Activity toMobile dialog.

How to do it...

First, we need to add the SwipeRefreshLayout widget and ListView to the activity layout, then we will implement the refresh listener in the Java code. Here are the detailed steps:

  1. Open activity_main.xml and replace the existing constraint layout with the following:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools...

Listing available sensors – an introduction to the Android Sensor Framework


Android includes support for hardware sensors using the Android Sensor Framework. The framework includes the following classes and interfaces:

  • SensorManager
  • Sensor
  • SensorEventListener
  • SensorEvent

Most Android devices include hardware sensors, but they vary greatly between different manufacturers and models. If your application utilizes sensors, you have two choices:

  • Specify the sensor in the Android Manifest
  • Check for the sensor at runtime

To specify your application uses a sensor, include the <uses-feature> declaration in the Android Manifest. Here is an example requiring a compass to be available:

<uses-feature android:name="android.hardware.sensor.compass" android:required="true"/>

If your application utilizes the compass, but does not require it to function, you should set android:required="false" instead; otherwise your application will not be available to install from Google Play.

Sensors are grouped into...

Reading sensor data – using Android Sensor Framework events


The previous recipe, Listing available sensors – an introduction to the Android Sensor Framework, provided an introduction to the Android Sensor Framework. Now, we'll look at reading sensor data using SensorEventListener. The SensorEventListener interface only has two callbacks:

  • onSensorChanged()
  • onAccuracyChanged()

When the sensor has new data to report, it calls onSensorChanged() with a SensorEvent object. This recipe will demonstrate reading a light sensor, but since all the sensors use the same framework, it's very easy to adapt this example to any of the other sensors. (See the list of sensor types available in the previous recipe's introduction.)

Getting ready

Create a new project in Android Studio and call it ReadingSensorData. Use the default Phone & Tablet options and select Empty Activity when prompted for the Activity Type.

How to do it...

We'll add a TextView to the activity layout to display sensor data, then we'll add...

Reading device orientation


Although the Android framework will automatically load new resources (such as the layout) upon orientation changes, there are times when you may wish to disable this behavior. If you wish to be notified of an orientation change instead of Android handling it automatically, add the following attribute to the Activity in the Android Manifest:

android:configChanges="keyboardHidden|orientation|screenSize" 

When any of the following configuration changes occur, the system will notify you through the onConfigurationChanged() method instead of handling it automatically:

  • keyboardHidden
  • orientation
  • screenSize

The onConfigurationChanged() signature is as follows:

onConfigurationChanged (Configuration newConfig) 

You'll find the new orientation in newConfig.orientation.

 

Note

Disabling the automatic configuration change (which causes the layout to be reloaded and state information to be reset) should not be used as a replacement for properly saving state information. Your application...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android 9 Development Cookbook - Third Edition
Published in: Oct 2018Publisher: PacktISBN-13: 9781788991216
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
Rick Boyer

Rick Boyer has been programming professionally for over 20 years. He has written apps on Windows, created websites, and coded for various mobile devices, including Windows CE, Windows Phone, and Android. Almost eight years ago, he took the plunge and started his own software consulting business, NightSky Development, focusing exclusively on Android development.
Read more about Rick Boyer