This implementation in your activity should work:
@Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_SPACE && event.getAction() == KeyEvent.ACTION_UP) { Log.d("test", "[Dispatch] Space bar pressed! " + event); return true; } return super.dispatchKeyEvent(event); }
The difference from your code is that I call super.dispatchKeyEvent()
for all other keys except SPACE_BAR. If dispatchKeyEvent returns true, then onKeyUp()
will not be triggered. Therefore, if you just want to observe the space event, just comment out the line //return true;
It also works great if you use the onKeyUp()
method. Do not use onKeyDown()
, it can be called several times if the user holds his finger for too long.
@Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_SPACE) { Log.d("test", "Space bar pressed!"); return true; } return super.onKeyUp(keyCode, event); }
Here I use a similar approach. If your if statement is a true handle event and returns true. For the rest of your keys, call super.onKeyUp();
At least, but most importantly, if you have a view (for example, EditText), which owns the current focus and keyboard, is displayed for this view, then the code above will not be called at all (in Activity). If so, you need to implement the TextView.OnEditorActionListener
listener and register a setOnEditorActionListener(TextView.OnEditorActionListener l)
call for this view.
viewWithFocus.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_SPACE && event.getAction() == KeyEvent.ACTION_UP) { Log.d("test", "[Editor] Space bar pressed! " + event);
Alternatively, you can override this view and implement onKepUp()
as described above.
Update
The hardware keyboard is working on the solution. Sorry to not check this more carefully.
From the documentation for Android
Note. When handling keyboard events with the KeyEvent class, you should expect that such keyboard events will only come from the hardware keyboard. You should never rely on getting an event key for any key using the soft key input method (on-screen keyboard).
However, I found how to overcome this problem. I based my research on the SearchView component and found that the following code would complete the task:
editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { char last = s.charAt(s.length()-1); if (' ' == last) { Log.i("test", "space pressed"); } } @Override public void afterTextChanged(Editable s) { } });
For IME actions, use TextView.OnEditorActionListener
.