articles

Home / DeveloperSection / Articles / Handling single and multi-touch in Android

Handling single and multi-touch in Android

Manoj Pandey4102 11-Mar-2015

Touch Gestures class describes how to write apps that allow users to interact with an app via touch gestures. Android provides a variety of APIs to help you create and detect gestures.

Although your app should not depend on touch gestures for basic behaviours (since the gestures may not be available to all users in all contexts), adding touch-based interaction to your app can greatly increase its usefulness and appeal.

The Android standard View class support touch events. You can react to touch events in your custom views and your activities. Android supports multiple pointers, fingers which are interacting with the screen.

The base class for touch support is the MotionEvent class which is passed to Views via the onTouchEvent() method. To react to touch events you override the onTouchEvent() method.

Single touch event-: The MotionEvent class provides the following constants to determine the action which was performed.

            Event                                                                    Description

         MotionEvent.ACTION_DOWN                        New touch started

         MotionEvent.ACTION_MOVE                         Finger is moving

         MotionEvent.ACTION_UP                               Finger went up

        MotionEvent.ACTION_CANCEL                       Current event has been cancelled, something  

                                                                                      else took control of the touch event

        MotionEvent.ACTION_POINTER_DOWN       Pointer down (multi-touch)

        MotionEvent.ACTION_POINTER_UP             Pointer up (multi-touch)

 

Multi touch-: Multi-touch is available since Android 2.0 and has been improved in the version 2.2. This description uses the API as of version 2.2.

The MotionEvent.ACTION_POINTER_DOWN and MotionEvent.ACTION_POINTER_UP are send starting with the second finger. For the first finger MotionEvent.ACTION_DOWN and MotionEvent.ACTION_UP are used.

 

Here I am creating a sample of single touch and multiple touch
Single Touch Example

1.      Create an android project and minimum sdk must be greater than 7

2.      Create a class and name as SingleTouchEventView with extends View

 

package com.example.androidtouchevent; 

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();

                // create Constructor

                public SingleTouchEventView(Context context, AttributeSet attrs) {

                                super(context, attrs);

                                paint.setAntiAlias(true);

                                paint.setStrokeWidth(6f);

                                paint.setColor(Color.BLACK);

                                paint.setStyle(Paint.Style.STROKE);

                                paint.setStrokeJoin(Paint.Join.ROUND);

                }

                // draw line

                @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;

                }

}

 

3.      Call this class on MainActicity.class

package com.example.androidtouchevent;

 

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

 

public class MainActivity extends Activity {

 

     @Override

     protected void onCreate(Bundle savedInstanceState) {

           super.onCreate(savedInstanceState);

           // setContentView(R.layout.activity_main);

           // Call SingleTouch event contructor

           setContentView(new SingleTouchEventView(this, null));

 

     }   

 

}

 

Run your application

Handling single and multi-touch in Android

 

Multi- Touch Example

4.    Create another class name as MultitouchView and extends with View

Add following code in this class

package com.example.androidtouchevent;

import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.graphics.PointF;

import android.util.AttributeSet;

import android.util.SparseArray;

import android.view.MotionEvent;

import android.view.View;

 

public class MultitouchView extends View {

 

  private static final int SIZE = 60;

 

  private SparseArray<PointF> mActivePointers;

  private Paint mPaint;

  // define color for touch event

  private int[] colors = { Color.BLUE, Color.GREEN, Color.MAGENTA,

      Color.BLACK, Color.CYAN, Color.GRAY, Color.RED, Color.DKGRAY,

      Color.LTGRAY, Color.YELLOW };

 

  private Paint textPaint;

 

  public MultitouchView(Context context, AttributeSet attrs) {

    super(context, attrs);

    initView();

  }

  private void initView() {

    mActivePointers = new SparseArray<PointF>();

    mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    // set painter color to a color you like

    mPaint.setColor(Color.BLUE);

    mPaint.setStyle(Paint.Style.FILL_AND_STROKE);

    textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    textPaint.setTextSize(20);

  }

 

  @Override

  public boolean onTouchEvent(MotionEvent event) {

 

    // get pointer index from the event object

    int pointerIndex = event.getActionIndex();

 

    // get pointer ID

    int pointerId = event.getPointerId(pointerIndex);

 

    // get masked (not specific to a pointer) action

    int maskedAction = event.getActionMasked();

 

    switch (maskedAction) {

    case MotionEvent.ACTION_DOWN:

    case MotionEvent.ACTION_POINTER_DOWN: {

      // We have a new pointer. Lets add it to the list of pointers

 

      PointF f = new PointF();

      f.x = event.getX(pointerIndex);

      f.y = event.getY(pointerIndex);

      mActivePointers.put(pointerId, f);

      break;

    }

    case MotionEvent.ACTION_MOVE: { // a pointer was moved

      for (int size = event.getPointerCount(), i = 0; i < size; i++) {

        PointF point = mActivePointers.get(event.getPointerId(i));

        if (point != null) {

          point.x = event.getX(i);

          point.y = event.getY(i);

        }

      }

      break;

    }

    case MotionEvent.ACTION_UP:

    case MotionEvent.ACTION_POINTER_UP:

    case MotionEvent.ACTION_CANCEL: {

      mActivePointers.remove(pointerId);

      break;

    }

    }

    invalidate();

 

    return true;

  }

  @Override

  protected void onDraw(Canvas canvas) {

    super.onDraw(canvas);

 

    // draw all pointers

    for (int size = mActivePointers.size(), i = 0; i < size; i++) {

      PointF point = mActivePointers.valueAt(i);

      if (point != null)

        mPaint.setColor(colors[i % 9]);

      canvas.drawCircle(point.x, point.y, SIZE, mPaint);

    }

    canvas.drawText("Total pointers: " + mActivePointers.size(), 10, 40 , textPaint);

  }

 

}

5.       Call on MainActivity.Class

package com.example.androidtouchevent;

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

 

public class MainActivity extends Activity {

 

     @Override

     protected void onCreate(Bundle savedInstanceState) {

           super.onCreate(savedInstanceState);

           // setContentView(R.layout.activity_main);

           // Call MultiTouch event contructor

           setContentView(new MultitouchView(this, null));

 

     }

 

}

 Now run your application 

If you run your application you will be able to draw on the screen with your fingers. Every device has an upper limit how many pointers are supported, test out how many simultaneous pointers your device supports.

 

Handling single and multi-touch in Android


Updated 07-Sep-2019

Leave Comment

Comments

Liked By