This is what bothered many people before, and I could not find the answer when I needed it. In pure XML, this is so. If we can use programming, and not just markup, we can do it with a little hack if you can. Essentially, we declare a multiLine editText, and then intercept the return key to avoid new lines.
First declaration in xml :
<EditText android:id="@+id/noReturnEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:imeOptions="actionDone" android:inputType="textMultiLine|textCapSentences" android:text="lorem ipsum \n dolor site amet helping stackoverflow" />
Yes, I know what you’re thinking: "Hey Juan, this is an EditText
and I want one liner, as in the gmail domain." I know, I know, but we will take care of it right now by deleting the behavior of the multi-line part that we don’t need, while maintaining the wrap with the text we really want.
Now the rest of the code :
EditText noReturnEditText = (EditText) findViewById(R.id.noReturnEditText); noReturnEditText.setOnKeyListener(new OnKeyListener(){ @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) return true; return false; } });
You can probably read the code quite easily, but in case someone needs an explanation, we set OnKeyListener
to EditText
we want it to be "oneline-multilinelike", and if the user presses the return key (KEYCODE_ENTER), we inform that the event is not propagated, returning true
which in this context means that we processed the event.
Result:
Considerations
Pressing the return key is not the only way to enter a new line. The user can copy / paste some text and get a multi-line record in a single-line EditText. Do not worry! We can remove the value before saving it or using it with something like
myData = rawText.replace(System.getProperty("line.separator"), " ");
What if I have a lot of EditText
views?
Well, you have two options. Do it one by one and stretch your eyes or do something like this by listing the views and looping around for each view.
//Declare the reusable listener OnKeyListener myListener = new OnKeyListener(){ @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) return true; return false; } } //Loop through the views int viewIds[] = {R.id.edittext1,R.id.edittext2,R.id.edittext3,R.id.edittext4}; for(int id : viewIds) ((EditText)findViewById).setOnKeyListener(myListener);