I ended up with a combination of Roberts and chirags answers:
((EditText)findViewById(R.id.search_field)).setOnEditorActionListener(
new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// Identifier of the action. This will be either the identifier you supplied,
// or EditorInfo.IME_NULL if being called due to the enter key being pressed.
if (actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_ACTION_DONE
|| event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
onSearchAction(v);
return true;
}
// Return true if you have consumed the action, else false.
return false;
}
});
Update:
The above code would some times activate the callback twice. Instead I've opted for the following code, which I got from the Google chat clients:
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// If triggered by an enter key, this is the event; otherwise, this is null.
if (event != null) {
// if shift key is down, then we want to insert the '
' char in the TextView;
// otherwise, the default action is to send the message.
if (!event.isShiftPressed()) {
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
}
return true;
}
return false;
}
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
}
return true;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…