EditText won't wrap its text
This is something that has bothered a lot of people before and I couldn't find an answer when I needed it. In pure XML, that is. If we can use programming and not just markup, we can do this with a little hack if you may. Basically, we are declaring a multiLine editText and then catching the return key to avoid new lines.
First the 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 "But hey, Juan this is a multiliner EditText
and I want a one liner like on the subject area of gmail". I know, I know, but we are going to take care of it right now, by removing the behavior of the multiline part we don't want, while keeping the text wrapping we do 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 are setting an OnKeyListener
to the EditText
we want to be "oneline-multilinelike" and if the user presses the return key (KEYCODE_ENTER) we tell the event not to propagate by returning true
which in this context means we've handled the event.
Result:
Considerations
Pressing the return key is not the only way of entering a new line. The user could copy/paste some text and end up with a multi-line entry on a single-line EditText. Worry not! We can strip the value before we store it or use it with something like
myData = rawText.replace(System.getProperty("line.separator"), " ");
What if I have lots of EditText
views?
Well, you basically have two options. Do it one by one and pull your eyes out or do something like this, its listing the views and looping 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);