2
votes

In preparing my Android App for Chromebooks and use with physical keyboards I want to distinguish in an EditText between receiving an "Enter" (keyEvent 66) and an "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 either 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: did any other Android Dev find a way to properly capture the Shift+Enter from a physical keyboard?

1

1 Answers

2
votes

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;
        }
    });