vogella training Android Training Eclipse Training

Android Touch

Lars Vogel

Version 0.6

16.08.2011

Revision History
Revision 0.1 03.06.2011 Lars
Vogel
Created
Revision 0.2 - 0.6 15.06.2011 - 16.08.2011 Lars
Vogel
bug fixes and enhancements

Touch in Android

This tutorial describes how to use touch in Android applications with Eclipse.


Table of Contents

1. Android Touch
1.1. Android Basics
1.2. Android Basics
2. Singletouch Example
3. ScaleGestureDetector
4. Thank you
5. Questions and Discussion
6. Links and Literature
6.1. Source Code
6.2. Android Resources
6.3. vogella Resources

1. Android Touch

1.1. Android Basics

Touch is an important input method for Android devices. The standard UI components (View) already support touch without the need of the developer to interfere. This article describes how to implement a touch interface in your Android application.

The base class for touch support is the class "MotionEvent". MotionEvent contains the touch related information. To react to touch events in your view or your activity you override the method "onTouchEvent()". This method must return a boolean value which indicates if the touch event has been consumed (true) or if the framework should still react to the touch event (false). If single input is used you can use the methods getX() and getY() to get the current position. Via getAction() you receive the action which was performed.

Table 1. Sample Table

Event Description
MotionEvent.ACTION_DOWN New touch started
MotionEvent.ACTION_MOVE Finger is moving
MotionEvent.ACTION_UP Finger went up
MotionEvent.ACTION_OUTSIDE Finger is leaving the UI component

Multitouch was introduced in Android 2.0 and has been improved in each Android version. This tutorial focus currently on SingleTouch and it is planned to extend this for multitouch.

1.2. Android Basics

The following assumes that you have already basic knowledge in Android development.

2. Singletouch Example

We will demonstrate Singletouch via an example with an own view. Create the Android project "de.vogella.android.touch.single" with the activity "SingleTouchView".

Create the following view class "SingleTouchEventView".

			
package de.vogella.android.touch.single;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class SingleTouchEventView extends View {
	private Paint paint = new Paint();
	private Path path = new Path();

	public SingleTouchEventView(Context context, AttributeSet attrs) {
		super(context, attrs);

		paint.setAntiAlias(true);
		paint.setStrokeWidth(6f);
		paint.setColor(Color.WHITE);
		paint.setStyle(Paint.Style.STROKE);
		paint.setStrokeJoin(Paint.Join.ROUND);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		canvas.drawPath(path, paint);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		float eventX = event.getX();
		float eventY = event.getY();

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			path.moveTo(eventX, eventY);
			return true;
		case MotionEvent.ACTION_MOVE:
			path.lineTo(eventX, eventY);
			break;
		case MotionEvent.ACTION_UP:
			// nothing to do
			break;
		default:
			return false;
		}

		// Schedules a repaint.
		invalidate();
		return true;
	}
}

		

Add this view to your activity.

			
package de.vogella.android.touch.single;

import android.app.Activity;
import android.os.Bundle;

public class SingleTouchActivity extends Activity {
	
/** Called when the activity is first created. */
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new SingleTouchEventView(this, null)); } }

If you run your application you will be able to draw on the screen with your finger (or with the mouse in the emulator).

3. ScaleGestureDetector

The ScaleGestureDetector class allows to determine the predefined gesture of increasing, decreasing the size of the object.

Create the Android project "de.vogella.android.touch.scaledetector" and the Activity "ScaleDetectorTest" and create the following view class "ImageViewWithZoom".

			
package de.vogella.android.touch.scaledetector;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;

public class ImageViewWithZoom extends View {
	private Drawable image;
	private float scaleFactor = 1.0f;
	private ScaleGestureDetector scaleGestureDetector;

	public ImageViewWithZoom(Context context) {
		super(context);
		image = context.getResources().getDrawable(R.drawable.icon);
		setFocusable(true);
		image.setBounds(0, 0, image.getIntrinsicWidth(),
				image.getIntrinsicHeight());
		scaleGestureDetector = new ScaleGestureDetector(context,
				new ScaleListener());
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		// Set the image bounderies
		canvas.save();
		canvas.scale(scaleFactor, scaleFactor);
		image.draw(canvas);
		canvas.restore();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		scaleGestureDetector.onTouchEvent(event);
		invalidate();
		return true;
	}

	private class ScaleListener extends
			ScaleGestureDetector.SimpleOnScaleGestureListener {
		@Override
		public boolean onScale(ScaleGestureDetector detector) {
			scaleFactor *= detector.getScaleFactor();

			// Don't let the object get too small or too large.
			scaleFactor = Math.max(0.1f, Math.min(scaleFactor, 5.0f));

			invalidate();
			return true;
		}
	}
}

		

Add this view to your activity.

			
package de.vogella.android.touch.scaledetector;

import android.app.Activity;
import android.os.Bundle;

public class ScaleDetectorTest extends Activity {
	
/** Called when the activity is first created. */
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new ImageViewWithZoom(this)); } }

If you run your application zyou should be able to shrink / enlarge the image via a multi-touch gesture (pitch zoom).

4. Thank you

Please help me to support this article:

Flattr this

5. Questions and Discussion

Before posting questions, please see the vogella FAQ. If you have questions or find an error in this article please use the www.vogella.com Google Group. I have created a short list how to create good questions which might also help you.

6. Links and Literature

6.1. Source Code

Source Code of Examples

6.3. vogella Resources

Eclipse RCP Training (German) Eclipse RCP Training with Lars Vogel

Android Tutorial Introduction to Android Programming

GWT Tutorial Program in Java and compile to JavaScript and HTML

Eclipse RCP Tutorial Create native applications in Java

JUnit Tutorial Test your application

Git Tutorial Put everything you have under distributed version control system