Game Development Reference
In-Depth Information
An
OnTouchListener
can be registered with any
View
implementation via the
View.setOnTouchListener()
method. The
OnTouchListener
will be called before the
MotionEvent
is dispatched to the
View
itself. We can signal to the
View
in our implementation of the
onTouch()
method that we have already processed the event by returning
true
from the method. If we
return
false
, the
View
itself will process the event.
The
MotionEvent
instance has three methods that are relevant to us:
ï?®
MotionEvent.getX()
and
MotionEvent.getY()
: These methods report the
x and y coordinates of the touch event relative to the
View
. The coordinate
system is defined with the origin in the top left of the view, with the x axis
pointing to the right and the y axis pointing downward. The coordinates are
given in pixels. Note that the methods return floats, and thus the coordinates
have subpixel accuracy.
ï?®
MotionEvent.getAction()
: This method returns the type of the touch event.
It is an integer that takes on one of the values
MotionEvent.ACTION_DOWN
,
MotionEvent.ACTION_MOVE
,
MotionEvent.ACTION_CANCEL
, or
MotionEvent.ACTION_UP
.
Sounds simple, and it really is. The
MotionEvent.ACTION_DOWN
event happens when the finger
touches the screen. When the finger moves, events with type
MotionEvent.ACTION_MOVE
are fired.
Note that you will always get
MotionEvent.ACTION_MOVE
events, as you can't hold your finger still
enough to avoid them. The touch sensor will recognize the slightest change. When the finger
is lifted up again, the
MotionEvent.ACTION_UP
event is reported.
MotionEvent.ACTION_CANCEL
events are a bit of a mystery. The documentation says they will be fired when the current gesture
is canceled. We have never seen that event in real life yet. However, we'll still process it and
pretend it is a
MotionEvent.ACTION_UP
event when we start implementing our first game.
Let's write a simple test activity to see how this works in code. The activity should display the
current position of the finger on the screen as well as the event type. Listing 4-3 shows what we
came up with.
Listing 4-3. SingleTouchTest.java; Testing Single-Touch Handling
package
com.badlogic.androidgames;
import
android.app.Activity;
import
android.os.Bundle;
import
android.util.Log;
import
android.view.MotionEvent;
import
android.view.View;
import
android.view.View.OnTouchListener;
import
android.widget.TextView;
public class
SingleTouchTest
extends
Activity
implements
OnTouchListener {
StringBuilder builder =
new
StringBuilder();
TextView textView;
public void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
textView =
new
TextView(
this
);