In preparing my Android App for Chromebooks use with physical keyboards I want to distinguish in an EditText between receiving an "Enter" (keyEvent 66)
and "Shift+Enter" (also keyEvent 66 apparently)
from a physical keyboard.
I have tried a number of different solutions, such as
dispatchKeyEvent(KeyEvent event)
in the activity. The event.getModifiers()
however always return 0, as do event.getMetaState(). keyEvent.isShiftPressed()
always returns false.onKeyDown(int keyCode, KeyEvent keyEvent)
in the activity with the same result. keyEvent.isShiftPressed()
always returns false as well.I have not found a way, whether using onKeyUp()
, onKeyPreIme()
, editText.setOnKeyListener(...)
, or with a editText.addTextChangedListener(new TextWatcher() {...})
.
I have not had any problems acquiring the Enter event
, however a Shift+Enter
is in all the ways I have tried indistinguishable from the Enter event
.
So my question is this: has any Android Dev found a way to properly capture the Shift+Enter
event from a physical keyboard?
i had the same problem and I fixed it by detecting "Shift" down and "Shift" up events, and define a boolean that store the state. this is my code, hope help you.
final boolean[] isPressed = {false};
inputEditText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
if (isPressed[0]) {
// Shift + Enter pressed
return false;
} else {
// Enter pressed
return true;
}
}
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) {
isPressed[0] = true;
return false;
}
if ((event.getAction() == KeyEvent.ACTION_UP) &&
(keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) {
isPressed[0] = false;
return false;
}
return false;
}
});