Game Development Reference
In-Depth Information
ï?®
MotionEvent.ACTION_POINTER_UP
: This is analogous to the previous action.
This gets fired when a finger is lifted up from the screen and more than one
finger is touching the screen. The last finger on the screen to be lifted will
produce a
MotionEvent.ACTION_UP
event. This finger doesn't necessarily
have to be the first finger that touched the screen.
Luckily, we can just pretend that those two new event types are the same as the old
MotionEvent.ACTION_UP
and
MotionEvent.ACTION_DOWN
events.
The last difference is the fact that a single
MotionEvent
can have data for multiple events. Yes,
you read that right. For this to happen, the merged events have to have the same type. In reality,
this will only happen for the
MotionEvent.ACTION_MOVE
event, so we only have to deal with this
fact when processing said event type. To check how many events are contained in a single
MotionEvent
, we use the
MotionEvent.getPointerCount()
method, which tells us the number
of fingers that have coordinates in the
MotionEvent
. We then can fetch the pointer identifier
and coordinates for the pointer indices 0 to
MotionEvent.getPointerCount() - 1
via the
MotionEvent.getX()
,
MotionEvent.getY()
, and
MotionEvent.getPointerId()
methods.
In Practice
Let's write an example for this fine API. We want to keep track of ten fingers at most (there's
no device yet that can track more, so we are on the safe side here). The Android device will
usually assign sequential pointer indices as we add more fingers to the screen, but it's not
always guaranteed, so we rely on the pointer index for our arrays and will simply display which
ID is assigned to the touch point. We keep track of each pointer's coordinates and touch state
(touching or not), and output this information to the screen via a
TextView
. Let's call our test
activity
MultiTouchTest
. Listing 4-4 shows the complete code.
Listing 4-4. MultiTouchTest.java; Testing the Multitouch API
package
com.badlogic.androidgames;
import
android.app.Activity;
import
android.os.Bundle;
import
android.view.MotionEvent;
import
android.view.View;
import
android.view.View.OnTouchListener;
import
android.widget.TextView;
@TargetApi
(5)
public class
MultiTouchTest
extends
Activity
implements
OnTouchListener {
StringBuilder builder =
new
StringBuilder();
TextView textView;
float
[] x =
new float
[10];
float
[] y =
new float
[10];
boolean
[] touched =
new boolean
[10];
int
[] id =
new int
[10];
private void
updateTextView() {
builder.setLength(0);
for
(
int
i = 0; i < 10; i++) {