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 newl开发者_StackOverflow社区ine but the text is displayed in multiple lines.
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);
}
}
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.
Property in XML
android:lines="5"
android:inputType="textPersonName"
This one works for me:
<EditText
android:inputType="textShortMessage|textMultiLine"
android:minLines="3"
... />
It shows a smiley instead of the Enter key.
Here's a more correct answer that does not display the enter key on the IME keyboard:
// IMPORTANT, do this before any of the code following it
myEditText.setSingleLine(true);
// IMPORTANT, to allow wrapping
myEditText.setHorizontallyScrolling(false);
// IMPORTANT, or else your edit text would wrap but not expand to multiple lines
myEditText.setMaxLines(6);
Also, you may replace setSingleLine(true)
with either, an explicit android:inputType
on the XML layout file, or setInputType(InputType.*)
on code – in which, the input type used, is anything that you know restricts the input to single lines only (i.e., anything that calls setSingleLine(true)
implicitly already).
Explanation:
What setSingleLine(true)
does is calling setHorizontallyScrolling(true)
and setLines(1)
implicitly, alongside with altering some IME keyboard settings to disable the enter key.
In turn, the call to setLines(1)
is like calling setMinLines(1)
and setMaxLines(1)
in one call.
Some input types (i.e., the constants from InputType.TYPE_*
) calls setSingleLine(true)
implicitly, or at least achieves the same effect.
Conclusion:
So to achieve what the OP wants, we simply counter those implicit settings by reverting those implicit calls.
The answer provided by @Andreas Rudolph contains a critical bug and shouldn't be used. The code causes an IndexOutOfBoundsException
when you past text inside the EditText
which contains multiple new-line characters. This is caused by the type of loop which is used, the Editable
object will call the afterTextChanged
method as soon as its contents change (replace, delete, insert).
Correct code:
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;
}
}
}
});
I'm testing this and it seems to work:
EditText editText = new EditText(context);
editText.setSingleLine(false);
editText.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_EMAIL_SUBJECT);
Try this:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER)
{
//Nothing
return true;
}
return super.onKeyDown(keyCode, event);
}
You can set it from the xml like this:
android:imeOptions="actionDone"
android:inputType="text"
android:maxLines="10"
don't forget android:inputType="text"
, if you don't set it, it doesn't work. I don't know why though.
Also don't forget to change maxLines
to your preferred value.
Simply add
android:singleLine="true"
to your EditText
Here is the solution....
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="150"
android:textSize="15dp"
android:imeOptions="actionDone"
android:inputType="text|textMultiLine"/>
Usage in java class
editText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, 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 (keyCode == KeyEvent.KEYCODE_ENTER);
}
});
The accepted answer worked so well until I copied text with line-breaks into into the EditText. So I added onTextContextMenuItem to monitor the paste action.
@Override
public boolean onTextContextMenuItem(int id) {
boolean ret = super.onTextContextMenuItem(id);
switch (id) {
case android.R.id.paste:
onTextPaste();
break;
}
return ret;
}
public void onTextPaste() {
if (getText() == null)
return;
String text = getText().toString();
text = text.replaceAll(System.getProperty("line.separator"), " ");
text = text.replaceAll("\\s+", " ");
setText(text);
}
You can change the action button from code
editText.imeOptions = EditorInfo.IME_ACTION_DONE
editText.setRawInputType(InputType.TYPE_CLASS_TEXT)
Xml
android:inputType="textMultiLine"
<EditText
android:id="@+id/Msg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:lines="5"
android:selectAllOnFocus="true"
android:hint="Skriv meddelande...\n(max 100tkn)"/>
EditText et = (EditText)findViewById(R.id.Msg);
String strTmp = et.getText().toString();
strTmp = strTmp.replaceAll("\\n"," ");
EditText textView = new EditText(activity);
...
textView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if(KeyEvent.KEYCODE_ENTER == keyEvent.getKeyCode()) {
return false;
}
.......
}
});
For a URI you could use:
android:inputType="textUri"
android:lines="1"
android:maxLength="128"
Otherwise android:inputType="textPersonName"
as mentioned above works for other EditText such user name, etc.
I will give another option so you don't have to subclass EditText. Create an InputFilter
that filters out linebreaks. Then use EditText.addInputFilter
.
Source code for such an input filter is here: https://gist.github.com/CapnSpellcheck/7c72830e43927380daf5205100c93977
You can pass 0 in the constructor, and it won't allow any newlines. Also, you can combine this with one of the other tweaks such as android:imeOptions="actionDone"
, as this will help improve the experience on some devices.
Adding this property to the EditText
XML works for me:
android:lines="1"
It lets the users input newline characters but the EditText
itself does not increase in height.
精彩评论