问题
I want to initialize a compose field with a listener for the return key. In the documentation it says that actionId
will be EditorInfo.IME_NULL
if it is being called due to the enter key being pressed. I compared actionId
for that value. It also says that if triggered by a returnkey we receive KeyEvent
object so i test it for KeyEvent.ACTION_UP
which is the value corresponding for the release of a key.
When i run the code it works for fine for a device running KitKat but in the other running Lollilop it doesn't consume return key and it doesn't call onEditorAction()
. It just inserts a new line. Here's the code:
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);
}
回答1:
Try this, this is how I do it using keyEvent
instead:
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;
}
});
Hope this helps;)
UPDATE
Make sure in your xml your editText has android:singleLine="true"
field.
来源:https://stackoverflow.com/questions/41260785/android-listener-for-return-key-on-edittext-not-working-for-every-device