我不明白为什么这段代码不起作用。仅检测退格键和返回键。监听器不会为任何其他键触发。我的设备是 Nexus One。
我试图覆盖 Activity 的 OnKeyDown 方法,结果更糟。唯一检测到的按钮是硬件后退按钮。
我看到了使用 TextWatcher 和 onTextChanged 的建议,虽然这在某些情况下可能有效,但这并不是真正的解决方法。例如,如果文本框为空,则不会检测到用户是否按下 BackSpace(Delete) 按钮。 那么有什么想法吗?
TextView txtInput = (TextView)findViewById(R.id.txtInput);
txtInput.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
makeToast(keyCode + " key pressed");
return true;
}
});
最佳答案
好的。我终于想出了如何做我想做的事,我对 Android 并不为此感到自豪。
我正在编写服务器/客户端应用程序,在客户端我必须打开 SoftKeyboard 并发送按下的键(字符和 DEL 键)...每次按下键时,该字符都会发送到服务器。如果按下 DEL,我将向服务器发送序列 {BS}。
为了做到这一点,我必须实现 TextWatcher 和 onTextChange,除了 EditText 为空且用户按下 DEL 键的情况外,它们运行良好。由于 EditText 没有变化,因此无法检测到按下 DEL 键。
除了 TextWatcher,我还必须实现附加到 EditText 控件的 onKeyListener。这个 onKeyListener 忽略 SoftKeyboard 上的所有键,除了 DEL 和 RETURN。不知道为什么?也许是一个错误?
这是我的代码:
TextView txtInput = (TextView)findViewById(R.id.txtInput);
txtInput.addTextChangedListener(inputTextWatcher);
txtInput.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.d(TAG, keyCode + " character(code) to send");
return false;
}
});
和 TextWatcher....
private TextWatcher inputTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) { }
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{ }
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d(TAG, s.charAt(count-1) + " character to send");;
}
};
关于android - onKeyListener 在虚拟键盘上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4282214/