Game Development Reference
In-Depth Information
The controls themselves are implemented as image buttons within the game layout (see the “Game
Layout” section). The
RelativeLayout
of the game allows the controls to overlap the video
ImageView
, as
shown in Figure 7-3. To set up events for the buttons, simply load the button widget using its ID and set
a touch listener:
findViewById(R.id.BUTTON_ID).setOnTouchListener(new View.OnTouchListener(){
public boolean onTouch(View v, MotionEvent evt) {
// ACTION_DOWN or ACTION_UP
int action = evt.getAction();
// …
}
});
Depending on the touch event action,
ACTION_DOWN
or
ACTION_UP
, you simply send a key event to the
native layer with the following code:
public static void sendNativeKeyEvent (int type, int sym) {
try {
Natives.keyEvent(type, sym);
} catch (UnsatisfiedLinkError e) {
Log.e(TAG, e.toString());
}
}
Listing 7-11 shows the
setupPanControls
function for the up, down, left, and right buttons of the
Doom controller.
Listing 7-11.
Controller Event Setup
private void setupPanControls() {
// Up
findViewById(R.id.btn_up).setOnTouchListener(
new View.OnTouchListener(){
public boolean onTouch(View v, MotionEvent evt) {
int action = evt.getAction();
if ( action == MotionEvent.ACTION_DOWN) {
Natives.sendNativeKeyEvent(Natives.EV_KEYDOWN
, DoomTools.KEY_UPARROW);
}
else if ( action == MotionEvent.ACTION_UP) {
Natives.sendNativeKeyEvent(Natives.EV_KEYUP
, DoomTools.KEY_UPARROW);
}
return true;
}
});
// Down
findViewById(R.id.btn_down).setOnTouchListener(
new View.OnTouchListener(){
public boolean onTouch(View v, MotionEvent evt) {