Android EditText 上 return 键的侦听器不适用于所有设备
Android listener for return key on EditText not working for every device
我想用 return 键的侦听器初始化一个撰写字段。在文档中它说 actionId
将是 EditorInfo.IME_NULL
如果由于按下回车键而被调用。我比较了 actionId
的那个值。它还说,如果由 return 键触发,我们会收到 KeyEvent
对象,所以我测试它的 KeyEvent.ACTION_UP
,这是释放键对应的值。
当我 运行 代码它适用于设备 运行ning KitKat 但在另一个 运行ning Lollilop 中它不消耗 return 密钥并且它不打电话 onEditorAction()
。它只是插入一个新行。这是代码:
public void setupChat() {
Log.i(LOG_TAG, "setupChat()");
oETConversation.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
Log.i(LOG_TAG, "onEditorAction()");
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String s = v.getText().toString();
sendMessage(s);
}
return true;
}
});
}
public void sendMessage(String s) {
Log.i(LOG_TAG, "sendMessage()");
Log.i(LOG_TAG, s);
}
试试这个,这就是我使用 keyEvent
的方法:
oETConversation.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_ENTER) {
String s = oETConversation.getText().toString();
sendMessage(s);
return true;
}
return false;
}
});
希望对您有所帮助;)
更新
确保在你的 xml 中你的 editText 有 android:singleLine="true"
字段。
我想用 return 键的侦听器初始化一个撰写字段。在文档中它说 actionId
将是 EditorInfo.IME_NULL
如果由于按下回车键而被调用。我比较了 actionId
的那个值。它还说,如果由 return 键触发,我们会收到 KeyEvent
对象,所以我测试它的 KeyEvent.ACTION_UP
,这是释放键对应的值。
当我 运行 代码它适用于设备 运行ning KitKat 但在另一个 运行ning Lollilop 中它不消耗 return 密钥并且它不打电话 onEditorAction()
。它只是插入一个新行。这是代码:
public void setupChat() {
Log.i(LOG_TAG, "setupChat()");
oETConversation.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
Log.i(LOG_TAG, "onEditorAction()");
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String s = v.getText().toString();
sendMessage(s);
}
return true;
}
});
}
public void sendMessage(String s) {
Log.i(LOG_TAG, "sendMessage()");
Log.i(LOG_TAG, s);
}
试试这个,这就是我使用 keyEvent
的方法:
oETConversation.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_ENTER) {
String s = oETConversation.getText().toString();
sendMessage(s);
return true;
}
return false;
}
});
希望对您有所帮助;)
更新
确保在你的 xml 中你的 editText 有 android:singleLine="true"
字段。