Get the key pressed in an EditText

前端 未结 2 1285
遥遥无期
遥遥无期 2021-01-19 10:08

I want to know which key has been pressed in an EditText. For example, if a is pressed, I want to get the value as \'a\'. How can I do this?

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-19 10:56

    You can set an onKeyListener() on the EditText, and retrieve the KeyCode that way. For example:

    editText.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            switch(keyCode) {
                case KeyEvent.KEYCODE_0:
                    //handle code for pressing 0
                    break;
                default:
                    break;
            }
        }
    });
    

    And in your switch statement, just handle whatever keycodes that you need. The full list can be found in the KeyEvent constants.

    EDIT: Keep in mind, for validation and that sort of thing, a TextWatcher, as nicholas mentioned, might be a preferable solution if you need to know what CHARACTER was entered (e.g. 'A' vs. 'a', as you'd have to handle the logic of whether the shift key was active or not in the key listener). If you just need to know what key was pressed, I'd recommend the OnKeyListener.

提交回复
热议问题