How to send key event to an edit text

2020-02-26 06:35发布

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.
}

10条回答
\"骚年 ilove
2楼-- · 2020-02-26 07:25

virsir , I suppose you are looking for dispatching hard keys programmatically.

For that you may try dispatch (KeyEvent.Callback receiver, KeyEvent.DispatcherState state, Object target) with an example at Back and other hard keys: three stories

Hope that helps.

查看更多
smile是对你的礼貌
3楼-- · 2020-02-26 07:27

Take a look at this article: creating-input-method.html. Basically, you can either manually send KeyEvents or you can manually edit and commit text around the cursor in the application's Input View.These are all done via your IME's InputConnection.

Hope this helps,

查看更多
Explosion°爆炸
4楼-- · 2020-02-26 07:28

Check for key events in your activity. for example, this code listens for back keypress:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK))
    {
    finish();
    }
    return super.onKeyDown(keyCode, event);
}
查看更多
Anthone
5楼-- · 2020-02-26 07:28

try implementing TextWatcher interface.

it has 3 methods which you need to override.

public void afterTextChanged(Editable s) {

    Log.v("afterTextChanged","here");
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    Log.v("beforeTextChanged","here");
}

public void onTextChanged(CharSequence s, int start, int before, int count) {
}

I think this will work.

查看更多
登录 后发表回答