Android Touch Screen Example Tutorial

Android Touch Screen Example Tutorial

As part of my new android application project to be release soon, I will be discussing in this android tutorial how to test the android touch sensor.

According to the Google Android Guides  – “Most Android-powered devices have built-in sensors that measure motion, orientation, and various environmental conditions. These sensors are capable of providing raw data with high precision and accuracy, and are useful if you want to monitor three-dimensional device movement or positioning, or you want to monitor changes in the ambient environment near a device. For example, a game might track readings from a device’s gravity sensor to infer complex user gestures and motions, such as tilt, shake, rotation, or swing”

This application will be a simple app in which the user will use his or her finger to draw a line on the device screen.

We are going to use a Custom View for this tutorial. If you don’t know what a Custom View is all about, it is simply a subclass of the default View class in Android.

In order to understand what we are planning to do, we are going to show a screen shot of what we will achieve in this tutorial as shown below.

Android Touch Screen Example Tutorial

Before we start, it is important for you to understand the tools and environment I used in this application development tutorial. Feel free to use any tools you are familiar with.

Windows 7

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 19

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidTouchSensor

Package: com.inducesmile.androidtouchsensor

Keep other default selections.

Continue to click on next button until Finish button is active, then click on Finish Button.

If you are using Android Studio as your choice IDE, the new project will create a default MainActivity.java file and the corresponding layout file. Open the two files because we are going to make use of it soon.

Lets move on to create our custom View. The custom View will be called TouchView and it will inherit from the default Android View Class. We are going to override three methods of the parent View Class – onSizeChanged(), onDraw() and onTouchEvent().

We create a Paint Object which will use in combination to the touch coordinates to draw a Path. The code snippet for the class is shown below.

package com.toscanyacademy.androidtouchscreen;

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 TouchView extends View {

    private float x;
    private float y;

    Paint drawPaint;
    private Path path = new Path();


    public TouchView(Context context) {
        super(context);
    }

    public TouchView(Context context, AttributeSet attrs) {
        super(context, attrs);
        drawPaint = new Paint(Paint.DITHER_FLAG);
        drawPaint.setAntiAlias(true);
        drawPaint.setColor(Color.parseColor("#5D4037"));
        drawPaint.setStyle(Paint.Style.STROKE);
        drawPaint.setStrokeJoin(Paint.Join.ROUND);
        drawPaint.setStrokeWidth(3);
        setWillNotDraw(false);
    }

    @Override
    protected void onSizeChanged(int w, int h, int width, int height) {
        super.onSizeChanged(w, h, width, height);
    }

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

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        x = event.getX();
        y = event.getY();
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                path.moveTo(x, y);
                return true;
            case MotionEvent.ACTION_MOVE:
                path.lineTo(x, y);
                break;
            default:
                return false;
        }
        invalidate();
        return true;
    }
}

You can see that the code is very simple to understand. You can look into the onDraw method to understand how the actual drawing takes place.

The next thing will do is to attach our Custom View to our Main layout file – activity_main.xml.

It is also possible to get the holder of the View object in our application MainActivity.java file and we will set the object of our custom View as a parameter for the setContentView() of the Activity class.

For simplicity, we are going to use the former. The complete code for our layout file is as shown.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/instruction"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/touch_test"
        android:textColor="#000"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_margin="16dp"
        android:padding="8sp"/>

    <FrameLayout xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/instruction"
        android:layout_centerHorizontal="true">

        <com.toscanyacademy.androidtouchscreen.TouchView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#ffffff" />

    </FrameLayout>

</RelativeLayout>

Since you choose the first option on how to use our custom View, we are not going to write any code in the MainActivity.java file. The whole interaction will be passed to our custom View and it will use the touch positions to draw lines.

The default code snippet of the MainActivity.java file is shown below.

package com.toscanyacademy.androidtouchscreen;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Now, when you run your application you will see the interface that looks similar to the sample that was shown earlier on.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email so that you will be among the first to receive our new post once it is published.

If you like this tutorial, please kindly download my new android app in Google play store by clicking the image below

OTHER INTERESTING POSTS:

One Response

Add a Comment