Reputation: 1
I want the keyboard to hide on Enter
for a certain EditText
.
I've implemented this:
myEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if ((keyEvent!= null) && (keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
InputMethodManager in = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(editTextAnswer.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
return true;
}
return false;
}
});
This works for a number of keyboards, but not the AOSP one (tested with both Jelly Bean and KitKat devices). I've tried adding
android:imeOptions="actionGo"
to the EditText
and checking the action ID, but that didn't work either. I added logging code within onEditorAction(...)
and nothing gets logged when I hit the Enter
key on the AOSP keyboard. Is there some way I can achieve the behaviour I'm looking for?
Upvotes: 0
Views: 1237
Reputation: 4186
Try setting an OnKeyListener:
myEditText.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
switch (arg1) {
case KeyEvent.KEYCODE_ENTER:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
return true;
default:
break;
}
return false;
}
});
and try changing your OnEditorActionListener to the following:
myEditText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView arg0, int actionId,
KeyEvent arg2) {
// hide the keyboard and search the web when the enter key
// button is pressed
if (actionId == EditorInfo.IME_ACTION_GO
|| actionId == EditorInfo.IME_ACTION_DONE
|| actionId == EditorInfo.IME_ACTION_NEXT
|| actionId == EditorInfo.IME_ACTION_SEND
|| actionId == EditorInfo.IME_ACTION_SEARCH
|| (arg2.getAction() == KeyEvent.KEYCODE_ENTER)) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
return true;
}
return false;
}
});
Depending on the EditText, different enter keys are shown, sometimes it's says done, sometimes enter, sometimes go. You need to use all the flags for the possible states of the enter button, in order to get it. The KEYCODE_ENTER isn't usually passed to the EditorActionListener, although I include it for physical keyboards, but you can catch KEYCODE_ENTER with the OnKeyListener.
Upvotes: 2