开发者

Get the key pressed in an EditText

开发者 https://www.devze.com 2023-03-09 07:08 出处:网络
I want to know which key has been pressed in an EditText. For example, if a is pressed, I w开发者_运维知识库ant to get the value as \'a\'. How can I do this?You can set an onKeyListener() on the EditT

I want to know which key has been pressed in an EditText. For example, if a is pressed, I w开发者_运维知识库ant to get the value as 'a'. How can I do this?


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.


Take a look at my answer here:

Validating edittext in Android

0

精彩评论

暂无评论...
验证码 换一张
取 消