The only thing that really worked for me in this case was to add an InputFilter
that prevents a newline \n
from being entered.
Code:
editText.setFilters(new InputFilter[]{new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source != null) {
String s = source.toString();
if (s.contains("\n")) {
return s.replaceAll("\n", "");
}
}
return null;
}
}});
And the interesting lines from my configuration:
<EditText
...
android:singleLine="true"
android:inputType="text|textMultiLine"
android:imeOptions="actionDone"
/>
And if you want to hide and unfocus your EditText
when pressing enter, replace the above code with this:
editText.setFilters(new InputFilter[]{new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source != null) {
String s = source.toString();
if (s.contains("\n")) {
// Hide soft keyboard
InputMethodManager imm = (InputMethodManager)MainActivity.this.getBaseContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
// Lose focus
editText.clearFocus();
// Remove all newlines
return s.replaceAll("\n", "");
}
}
return null;
}
}});