I want to start an activity when the user presses the space bar. My code is not detecting when the space bar is clicked.
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.KEYCODE_SPACE) {
Toast.makeText(MainActivity.this, "YOU CLICKED SPACE KEY",
Toast.LENGTH_LONG).show();
return true;
}
Toast.makeText(MainActivity.this, "Didnt work", Toast.LENGTH_SHORT)
.show();
return super.dispatchKeyEvent(e);
};
}
You can either set the listener to a View
that has current focus, or use dispatchKeyEvent
in your Activity
, as seen in this answer.
Both will work.
Answer for your comments: If you've followed my link, you've probably implemented Activity.dispatchKeyEvent(KeyEvent)
by now. :-)
The code doesnt register anykey i press, but when i push the back key it toasts for me "didnt work"
Do you happen to be using the emulator? I ask that because the latest SDK seems to have some problems with the emulator keyboard. The special keys (DPAD, HOME, BACK etc.) work, but the onscreen, QWERTY keyboard does not register any presses. The physical keyboard in my laptop won't register any presses either.
Don't ask me why.
And I say that because this week I posted the answer in the link, and it was working fine. The change is that I updated the Android SDK to R20/JB this morning, so I guess it could be a factor.
However, it will just work on a real device. I've just connected a physical keyboard to my tablet (P7510 / Honeycomb 3.2), and it listens to space presses just fine.
In case you're still doubting, here is proof: :-)
public abstract boolean onKey (View v, int keyCode, KeyEvent event)
This function can be used to check that which key is pressed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With