Android Single And Multiple Touch Event Example

Android provides single and multiple touch support. If you want to respond to the touch event, you must create an instance of the android.view.View.OnTouchListener and override it’s onTouch(View view, MotionEvent motionEvent) method. Then register the listener to the view object use the view’s setOnTouchListener method.

1. Android Multi-touch Introduction.

  1. If you implement multi-touch on the android device screen surface, each touch is treated as a touch pointer. Each touch pointer has a unique id that will not be changed during the action.
  2. And the touch event is stored in the MotionEvent object, this object stores action-related information such as touch pointer count, pointer id, event action, action index, action x coordinate, and y coordinate.
  3. View object and MotionEvent object are passed as input parameters in the onTouch method. View object is where the touch event takes place. MotionEvent‘s getAction() method will return current event’s action as an integer value.

1.1 MotionEvent getAction() Method Returned Action Values.

  1. MotionEvent.ACTION_DOWN: Single touch pointer down.
  2. MotionEvent.ACTION_UP: Single touch pointer up.
  3. MotionEvent.ACTION_MOVE: The action between touch down and touch up action.
  4. MotionEvent.ACTION_POINTER_DOWN: The second touch pointer down in the multi-touch scenario.
  5. MotionEvent.ACTION_POINTER_UP: The second touch pointer up in the multi-touch scenario.
  6. MotionEvent.ACTION_HOVER_ENTER: Drag one view hover another view when entering the second view’s area.
  7. MotionEvent.ACTION_HOVER_MOVE: Dag one view hover another view and move in the second view’s scope.
  8. MotionEvent.ACTION_HOVER_EXIT: Drag one view hover another view when exits the second view’s area.

1.2 MotionEvent Other Methods.

  1. getPointerCount(): Return total touch pointer count, there are at least one touch pointer.
  2. getPointerId(int pointerIndex): Return pointer id by pointer index. The pointer id is unique.
  3. getActionIndex(): Get action index.
  4. getX(int pointerIndex): Get touch pointer x coordinate.
  5. getY(int pointerIndex): Get touch pointer y coordinate.

2. Android Multi-touch Example.

  1. There are two TextView objects in this example. The first TextView displays the first touch pointer status info. The second TextView displays the second touch pointer status info.
    android-single-and-multi-touch-example
  2. To implement the single touch effect in the android virtual device, just press down the left mouse key and drag in the android emulator then you can see the first TextView displays the touch pointer’s id, action value, action index, and x, y coordinates.
    android-single-touch-example
  3. To implement multiple touch actions in the android emulator, you can press Alt ( or Ctrl ) + left mouse key simultaneously in Windows and Linux, and command + mouse key in macOS. Then the second TextView will display the second touch pointer status info in it.
    android-multiple-touch-example
  4. You can also see the log data output printed in the android Logcat console.

3. Android Multiple Touch Example Source Code.

  1. Just create an android project with empty activity template. Then write the below code in related files.

3.1 Main Activity Java File.

  1. MainActivity.java
    package com.dev2qa.multipletouch;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.MotionEvent;
    import android.view.View;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    
    public class MainActivity extends AppCompatActivity {
    
        private static String TAG_MULTIPLE_TOUCH = "MULTIPLE_TOUCH";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            setTitle("dev2qa.com - Android Multiple Touch Example.");
    
            final TextView pointerOneStatusTextView = (TextView)findViewById(R.id.multi_touch_pointer1);
    
            final TextView pointerTwoStatusTextView = (TextView)findViewById(R.id.multi_touch_pointer2);
    
            LinearLayout layout = (LinearLayout)findViewById(R.id.multi_touch_layout);
            layout.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
    
                    // Get total pointer number.
                    int totalPointerCount = motionEvent.getPointerCount();
    
                    // Loop for each pointer.
                    for(int i=0;i<totalPointerCount;i++)
                    {
                        StringBuffer pointerStatusBuf = new StringBuffer();
    
                        // Get pointer id.
                        int pointerId = motionEvent.getPointerId(i);
                        pointerStatusBuf.append("Pointer Id : ");
                        pointerStatusBuf.append(pointerId);
                        pointerStatusBuf.append(" . ");
    
                        // Get pointer action.
                        pointerStatusBuf.append("Action : ");
    
                        int action = motionEvent.getAction();
    
                        if(action == MotionEvent.ACTION_DOWN)
                        {
                            pointerStatusBuf.append("Down. ");
                        }else if(action == MotionEvent.ACTION_UP)
                        {
                            pointerStatusBuf.append("Up. ");
                        }else if(action == MotionEvent.ACTION_POINTER_DOWN)
                        {
                            pointerStatusBuf.append("Pointer Down. ");
                        }else if(action == MotionEvent.ACTION_POINTER_UP)
                        {
                            pointerStatusBuf.append("Pointer Up. ");
                        }else if(action == MotionEvent.ACTION_MOVE)
                        {
                            pointerStatusBuf.append("Move. ");
                        }else if(action == MotionEvent.ACTION_HOVER_ENTER)
                        {
                            pointerStatusBuf.append("Hover Enter. ");
                        }else if(action == MotionEvent.ACTION_HOVER_MOVE)
                        {
                            pointerStatusBuf.append("Hover Move. ");
                        }else if(action == MotionEvent.ACTION_HOVER_EXIT)
                        {
                            pointerStatusBuf.append("Hover Exit. ");
                        }else if(action == MotionEvent.ACTION_POINTER_2_DOWN)
                        {
                            pointerStatusBuf.append("Pointer 2 Down. ");
                        }else if(action == MotionEvent.ACTION_POINTER_2_UP)
                        {
                            pointerStatusBuf.append("Pointer 2 Up. ");
                        }else
                        {
                            pointerStatusBuf.append(action + ". ");
                        }
    
    
                        // Get action index.
                        int actionIndex = motionEvent.getActionIndex();
                        pointerStatusBuf.append("Action Index : ");
                        pointerStatusBuf.append(actionIndex);
                        pointerStatusBuf.append(" . ");
    
                        // Get pointer X coordinates.
                        float x = motionEvent.getX(i);
    
                        // Get pointer Y coordinates.
                        float y = motionEvent.getY(i);
    
                        pointerStatusBuf.append("X : ");
                        pointerStatusBuf.append(x);
                        pointerStatusBuf.append(" , Y : ");
                        pointerStatusBuf.append(y);
    
                        // Display the pointer info in logcat console.
                        Log.d(TAG_MULTIPLE_TOUCH, pointerStatusBuf.toString());
    
                        if(pointerId == 0)
                        {
                            // First textview display first touch pointer status info.
                            pointerOneStatusTextView.setText(pointerStatusBuf.toString());
                        }else
                        {
                            // Second textview display second touch pointer status info.
                            pointerTwoStatusTextView.setText(pointerStatusBuf.toString());
                        }
                    }
    
                    // Tell android system event has been consumed by this listener.
                    return true;
                }
            });
        }
    }

3.2 Layout XML File.

  1. activity_main.xml
    <LinearLayout
        android:id="@+id/multi_touch_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center">
    
        <TextView
            android:id="@+id/multi_touch_pointer1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Multiple touch pointer one status data."
            android:textAllCaps="false"
            android:gravity="center"
            android:textSize="20dp"
            android:layout_marginBottom="30dp"/>
    
        <TextView
            android:id="@+id/multi_touch_pointer2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Multiple touch pointer two status data."
            android:textAllCaps="false"
            android:gravity="center"
            android:textSize="20dp"/>
    
    </LinearLayout>
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

3 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Jefer
Jefer

Thanks for the example! 🙂

Val
Val

Hi Jerry,

thank you for the MultipleTouch example. I was able to build and run the app using your source code. I have a couple of questions.

1. I have two Bluetooth wireless mouse paired with my android phone. I want to use each one of them as separate touch pointer. Currently in your example they are treated as a single touch pointer. How do I do that? Any suggestions and code snippets are greatly appreciated.

2. How do I get the X,Y coordinates of the touch-potter when it is hovering (left button is not touched)?

3
0
Would love your thoughts, please comment.x
()
x