Game Development Reference
In-Depth Information
new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent evt) {
int action = evt.getAction();
final ImageButton b = (ImageButton) v;
// button down
if (action == MotionEvent.ACTION_DOWN) {
// change button image
b.setImageResource(R.drawable.snes_select1);
// Send key to native layer
sendEvent(MotionEvent.ACTION_DOWN,
KeyEvent.KEYCODE_ENTER);
}
// Button up
else if (action == MotionEvent.ACTION_UP) {
// switch image
b.setImageResource(R.drawable.snes_select0);
sendEvent(MotionEvent.ACTION_UP,
KeyEvent.KEYCODE_ENTER);
}
return true;
}
});
First, the button is extracted from the game layout using its ID by calling
mView.findViewById(R.
id.btn_select)
, where
btn_select
is the ID of the select button described in the game layout XML
(
wolf.xml
). Next, it listens for touch events by calling
setOnTouchListener
and implementing the touch
listener interface. Whenever the user touches a button, the controller will send the Android key code to
the listener (by calling
onTouch
). The listener, in turn, will process the key code and react appropriately.
Note that when the user presses the controller, it will receive a
MotionEvent.ACTION_DOWN
event. When
this happens the corresponding button image will be swapped with a pressed image using
button.setImageResource(BUTTON_DOWN_IMAGE_RESID)
. The same goes for the
ACTION_UP
event. This helps
with the lack of sensitivity when using touch interfaces as opposed to a keyboard. Many users complain
about this fact. Figure 6-6 shows the image resources used by the controller to implement this
mechanism.