Handling the multi-touch in a view

In this post you find a full example about how to

  • extend a view to draw, in this case, a circle where you touch the screen
  • implement a listener on a view to handle the multi-touch

In this app the screen is divided into two parts:

  • a top area displaying the data related to the touch:
    1. pointer index: index of an array where the touch information is stored
    2. pointer ID: unique and time constant identifier of a touch
    3. x coordinate of the center
    4. y coordinate of the center
    5. action: action on the touch
  • a bottom area containing the view and a red circle for the first touch and a green circle for the second touch

The following steps show the most important files of this app:

  1., the main activity

    from the line 51 onTouchListener I implement the class onTouchListener to handle events for the following actions:

    • ACTION_DOWN: first touch
    • ACTION_MOVE: moving touches
    • ACTION_CANCEL: break of the event (for example the display turns off)
    • ACTION_UP: release of the latest touch
    • ACTION_POINTER_DOWN: a touch after the first
    • ACTION_POINTER_UP: release of a touch with at least one touch yet

    note how I get the event data:

    • action = event.getActionMasked()
    • pointer index = event.getActionIndex() or with a loop from 0 to event.getPointerCount() for the actions (ACTION_MOVE e ACTION_CANCEL) that may relate to multiple touches at the same time
    • pointer id = event.getPointerId([pointer index])
    • x = event.getX([pointer index])
    • y = event.getY([pointer index])

    then I call private methods setTextViews(), moveCircle() and deleteCircle() to which the pointer index has never passed but the pointer id because the pointer id identifies the touch
    at line 187 the method invalidate() method calls the onDraw() method of the TouchView class to redraw the view

  2. res/layout/activity_main.xml, the layout


    this class extends the class View and overrides two methods

    • onDraw(): it redraws the view, the white background and two circles
    • onMeasure(): it sizes the view, it is not much important in this example

Launch the app and touch the screen:

You can download the project here.

One reply on “Handling the multi-touch in a view”

Leave a Reply

Your email address will not be published. Required fields are marked *

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