Reputation: 670
I tried many combinations of inputType, singleLine and maxLines, but I just can't get the behavior that I want.
Basically, I want the EditText to be a single string with no new lines allowed, but also to expand vertically if the string is longer than it's initial size. (all text needs to be displayed on screen)
textMultiLine expands when the string is long, but it does not prevent the usage of the new line character. singleLine has no effect in this case and maxLines simply changes the size of the box while you can still create new lines.
Anything other than textMultiLine does not expand vertically and the text will simply scroll horizontally if it's too long to fit.
Upvotes: 5
Views: 2654
Reputation: 28229
As I already mentioned in my comment, you listen for changes using TextWatcher. Unfortunately, there's (as of writing this answer) no other ways of doing this. As per your second comment though, here's an optimization suggestion.
Listeners can be classes, and they can be standalone classes. It doesn't have to be the current class or an anonymous inner class. For an instance, you can create a class like this:
public class SingleLineET implements TextWatcher {
EditText et;
public SingleLineET(EditText et){
this.et = et;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String converted = s.toString();
if(converted.contains("\n")){
//There are occurences of the newline character
converted = converted.replace("\n", "");
et.setText(converted);
}
}
@Override
public void afterTextChanged(Editable s) {
}
}
And whereever you want to have a listener, you simply do:
EditText theET = ...;
theET.addTextChangedListener(new SingleLineET(theET));
And like that you cut down the amount of places you need the same boilerplate code.
There may be some alternative in a later release of Android (or someone creates a view that automates this) but until then, using a class instead of manually creating code for it every time at least cuts down some lines
Upvotes: 2