Android keyListener working well on emulator, but not on device
I am working on the first stage of making a game. I have a drawable that I want to move around on the screen while the dpad arrows are being held down.
I set up a custom view, overrode onKeyDown and onKeyUp and I have a switch statement to identify the key being pressed. If a key is pressed, a boolean for that key goes to true. If the key is let up, the boolean goes to false. In another routine, the boolean is checked and the movement updated.
The problem is, the device I am testing this on is the G2, which has it's own unique keyboard with no dpad, so I also did i,j,l,m as arrows for movement. (see here, click on image) In the android emulator, my setup and movement works well. However, on the actual device, the drawable does not respond to any key press at all. My brother is testing this for me (my phone has no keyboard) so I can't debug on the actual device.
My questions are these: Are the KeyEvent.KEYCODE_* constants different for different keyboards (i.e开发者_运维问答. qwerty, non-qwerty, etc.)? Do I need to specify in the code a particular keyboard to use (e.g. keymap)?
Any help or suggestions are welcome. Thanks.
If needed, here is an example of my doKeyDown routine called from onKeyDown (very much based on the LunarLander example source):
boolean doKeyDown(int keyCode, KeyEvent msg) {
synchronized (mSurfaceHolder) {
// Log.d("KeyDown", "The key pressed was:" + keyCode);
// Log.d("KeyDown", "UP: " + mMove_Up + " DOWN: " + mMove_Down + " LEFT: " + mMove_Left +" RIGHT: " + mMove_Right);
mIsDown = false;
boolean handled = false;
switch (keyCode)
{
case KeyEvent.KEYCODE_DPAD_UP:
mMove_Up = true;
handled = true;
break;
case KeyEvent.KEYCODE_I: //Also up
mMove_Up = true;
handled = true;
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
mMove_Down = true;
handled = true;
break;
case KeyEvent.KEYCODE_M: //Also down
mMove_Down = true;
handled = true;
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
mMove_Left = true;
handled = true;
break;
case KeyEvent.KEYCODE_J: // Also left
mMove_Left = true;
handled = true;
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
mMove_Right = true;
handled = true;
break;
case KeyEvent.KEYCODE_L: // Also right
mMove_Right = true;
handled = true;
break;
}
return handled;
}
}
Just so anyone looking later with the same problem can figure this out, I fixed the problem. It was a noob/rookie mistake.
All I did was add 2 lines (I'm pretty sure only the first was necessary) to the constructor of my custom View:
setFocusable(true);
and
setFocusableInTouchMode(true);
Apparently these are necessary for the view to be able to get the key commands (but strangely it worked without them in the emulator). Verified working on hardware with these lines. Problem solved
精彩评论