Game Development Reference
In-Depth Information
textView.setText("Touch and drag (one finger only)!");
textView.setOnTouchListener(
this
);
setContentView(textView);
}
public boolean
onTouch(View v, MotionEvent event) {
builder.setLength(0);
switch
(event.getAction()) {
case
MotionEvent.
ACTION_DOWN
:
builder.append("down, ");
break
;
case
MotionEvent.
ACTION_MOVE
:
builder.append("move, ");
break
;
case
MotionEvent.
ACTION_CANCEL
:
builder.append("cancel", ");
break
;
case
MotionEvent.
ACTION_UP
:
builder.append("up, ");
break
;
}
builder.append(event.getX());
builder.append(", ");
builder.append(event.getY());
String text = builder.toString();
Log.d("TouchTest", text);
textView.setText(text);
return true
;
}
}
We let our activity implement the
OnTouchListener
interface. We also have two members: one for
the
TextView
, and a
StringBuilder
we'll use to construct our event strings.
The
onCreate()
method is pretty self-explanatory. The only novelty is the call to
TextView.setOnTouchListener()
, where we register our activity with the
TextView
so that it
receives
MotionEvent
s.
What's left is the
onTouch()
method implementation itself. We ignore the
view
argument, as
we know that it must be the
TextView
. All we are interested in is getting the touch event type,
appending a string identifying it to our
StringBuilder
, appending the touch coordinates, and
updating the
TextView
text. That's it. We also log the event to LogCat so that we can see
the order in which the events happen, as the
TextView
will only show the last event that we
processed (we clear the
StringBuilder
every time
onTouch()
is called).
One subtle detail in the
onTouch()
method is the return statement, where we return
true
.
Usually, we'd stick to the listener concept and return
false
in order not to interfere with the
event-dispatching process. If we do this in our example, we won't get any events other than
the
MotionEvent.ACTION_DOWN
event. So, we tell the
TextView
that we just consumed the event.
That behavior might differ between different
View
implementations. Luckily, we'll only need three
other views in the rest of this topic, and those will happily let us consume any event we want.