Prevent enter key on EditText but still show the text as multi-line
How do I make an EditText on Android such that the user may not enter a multi-line text, but the display is still multi-line (i.e. there is word-wrap instead of the text going over to the right)?
It's similar to the built-in SMS application where we can't input newline but the text is displayed in multiple lines.
Solution 1:
I would subclass the widget and override the key event handling in order to block the Enter
key:
class MyTextView extends EditText
{
...
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode==KeyEvent.KEYCODE_ENTER)
{
// Just ignore the [Enter] key
return true;
}
// Handle all other keys in the default way
return super.onKeyDown(keyCode, event);
}
}
Solution 2:
This is a method, where you don't have to override the EditText class. You just catch and replace the newlines with empty strings.
edittext.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
/*
* The loop is in reverse for a purpose,
* each replace or delete call on the Editable will cause
* the afterTextChanged method to be called again.
* Hence the return statement after the first removal.
* http://developer.android.com/reference/android/text/TextWatcher.html#afterTextChanged(android.text.Editable)
*/
for(int i = s.length()-1; i >= 0; i--){
if(s.charAt(i) == '\n'){
s.delete(i, i + 1);
return;
}
}
}
});
Credit to Rolf for improvement on an earlier answer.
Solution 3:
Property in XML
android:lines="5"
android:inputType="textPersonName"