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?
Take a look at my answer here:
Validating edittext in Android
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.