Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send key event to an edit text

For example, send a backspace key to the edit text control to remove a character or send a char code like 112 to append a character in the edittext control programmatically.

Actually, I need a method like

void onKeyReceived(int keyCode)
{
  // here I would like to append the keyCode to EditText, I know how to add a visible character, but what about some special keys, like arrow key, backspace key.
}
like image 915
virsir Avatar asked Jan 24 '11 05:01

virsir


1 Answers

To send a simulated backspace key press to an EditText you have to send both key press and release events. Like this:

mEditText.dispatchKeyEvent(new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
    KeyEvent.KEYCODE_DEL, 0));
mEditText.dispatchKeyEvent(new KeyEvent(0, 0, KeyEvent.ACTION_UP,
    KeyEvent.KEYCODE_DEL, 0));

This can be used to send any other key code, not just delete.

like image 195
Torben Avatar answered Oct 11 '22 09:10

Torben