Thursday, September 2, 2010

Use Keyboard and Touch Screen Input in Android Game

Just a few things you need here, but this can be really frustrating if you don't know what's happening:
1.You must keep your view in focus when android enters touch mode.
2.Your view must be in focus.
3.You must have an onkeydown listener of some sort.


So to accomplish these, in your View constructor:

1.this.setFocusable(true); //allow the view to be focused
this.setFocusableInTouchMode(true); // allow the view to be focused while in touch mode
2. this.requestFocus(); //set the focus on this view

Then in your View class:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.d("-------------------->code", Integer.toString(keyCode));
if (keyCode == KeyEvent.KEYCODE_FOCUS) {
//handle focus button pressed
return true;
}
return false;
}

Returning true tells android you have consumed the keypress. Returning false passes it along to other listeners.

No comments:

Post a Comment