[英]Android how to detect “delete” button press on keyboard to delete a single character?
I'm working on a remote control app and need to detect when a user pressed the <x
delete button on an empty text field to send this character over and delete something from a remote machine. 我正在使用一个远程控制应用程序,需要检测用户何时按下空白文本字段上的<x
删除按钮,以发送该字符并将其从远程计算机中删除。
How can I detect that the user pressed <x
Delete button on Android keyboard? 如何检测到用户按下了Android键盘上的<x
删除按钮?
I tried to ad on key listener, but that did not seem to work. 我试图在关键监听器上做广告,但这似乎没有用。
final EditText edittext = (EditText) findViewById(R.id.editText);
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
Log.i("KEYCODE", "" + keyCode);
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
return false;
} else if (edittext.length() == 0) {
if(keyCode == KeyEvent.KEYCODE_DEL) {
//perform erase when the text field is empty
}
}
return false;
}
});
I know I am late, but hope this will help someone else. 我知道我迟到了,但是希望这对其他人有帮助。 There is no direct way to do this using a listener, but if you look into the documentation of onTextChanged Listener you will find this: 没有使用侦听器执行此操作的直接方法,但是如果您查看onTextChanged侦听器的文档,则会发现以下内容:
This method is called to notify you that, within s , the count characters beginning at start have just replaced old text that had length before . 调用此方法是为了通知您,在s内,从start开始的count字符刚刚替换了早于的旧文本。
So in case of a backspace you will have this condition: 因此,在退格的情况下,您将遇到以下情况:
Within s (the editable view), 0 characters beginning at start (depends where the cursor is) have replaced old text that had length before (it's value will be generally 1, unless user first selected some text and then hit backspace) 在s (可编辑视图)内,从开始 (取决于光标所在的位置) 开始的 0个字符替换了之前具有长度的旧文本(其值通常为1,除非用户首先选择一些文本然后按退格键)
So if count == 0 you can assume that delete key was pressed. 因此,如果count == 0,则可以假定已按下删除键。
You can't use a View.OnKeyListener
for software keyboards. 您不能将View.OnKeyListener
用于软件键盘。
View.OnKeyListener: View.OnKeyListener:
Interface definition for a callback to be invoked when a hardware key event is dispatched to this view. 在将硬件键事件调度到此视图时要调用的回调的接口定义。 This is only useful for hardware keyboards; 这仅对硬件键盘有用。 a software input method has no obligation to trigger this listener . 软件输入方法没有义务触发此侦听器 。
Source: http://developer.android.com/reference/android/view/View.OnKeyListener.html 来源: http : //developer.android.com/reference/android/view/View.OnKeyListener.html
Use the method DispatchKeyEvent : 使用方法DispatchKeyEvent:
@Override public boolean dispatchKeyEvent(@NonNull KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
// ...
}
return super.dispatchKeyEvent(event);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.