Reputation: 125
I have a multi lines Edittext with a text (don't content "\n"), a font size (sp) and the length of text > Edittext.width(). I want to get length of the first line in EditText. How can I do it?
Upvotes: 3
Views: 1364
Reputation: 16691
One option could be to read the text and then get the index of the newline character, which is essentially the length of the string prior to it:
int firstLineLength = myEditText.getText().toString().indexOf("\n");
As an alternative, if you ever need to do this with other lines you can simply split the whole string based on the newline character:
String[] lines = myEditText.getText().toString().split("\n");
EDIT
Keep in mind that indexOf() will return -1 if an occurrence is not found. So if your EditText has one and only one string, you'll get a -1 line length so be prepared to check against that:
int lineEndIndex = myEditText.getText().toString().indexOf("\n");
int firstLineLength;
if(lineEndIndex == -1) {
firstLineLength = myEditText.getText().toString().length();
} else {
firstLineLength = lineEndIndex;
}
Upvotes: 4