如何将关键事件发送到编辑文本

vir*_*sir 12 java android android-edittext

例如,将退格键发送到编辑文本控件以删除字符或发送字符代码(如112)以编程方式在edittext控件中附加字符.

实际上,我需要一个类似的方法

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.
}
Run Code Online (Sandbox Code Playgroud)

Tor*_*ben 20

要将模拟退格键发送到EditText,您必须发送按键和释放事件.像这样:

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));
Run Code Online (Sandbox Code Playgroud)

这可用于发送任何其他密钥代码,而不仅仅是删除.


dav*_*e.c 7

您的问题并不是那么清楚,但我认为您想要TextView在按下某些按钮时修改/附加文本.如果是这样,您需要一些现有答案的组合.

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    (TextView) textView = (TextView) findViewById(R.id.myTextView);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    switch(keyCode) {
    case KeyEvent.KEYCODE_BACK:
        // user pressed the "BACK" key.  Append "_back" to the text
        textView.append("_back");
        return true;
    case KeyEvent.KEYCODE_DEL:
        // user pressed the "BACKSPACE" key.  Append "_del" to the text
        textView.append("_del");
        return true;
    default:
        return super.onKeyDown(keyCode, event);
    }
}
Run Code Online (Sandbox Code Playgroud)

是否为true您处理的每个案件(如上所述)返回或super.onKeyDown(keyCode, event);在您的switch陈述后始终返回将取决于您的确切要求.检查文档中的行为onKeyDown

如果不是在每种情况下附加文本而是要删除字符,或者移动光标,则可以在每个case语句中执行此操作.查看可以调用的不同方法的TextView文档.另请查看KeyEvent文档以获取可以检查的密钥列表.


Ama*_*lam 1

检查您活动中的关键事件。例如,此代码监听back按键:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK))
    {
    finish();
    }
    return super.onKeyDown(keyCode, event);
}
Run Code Online (Sandbox Code Playgroud)