Danh Nguyen
Danh Nguyen

Reputation: 125

How to get length of first line in Edittext android?

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?

You can see the photo

Upvotes: 3

Views: 1364

Answers (1)

AdamMc331
AdamMc331

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

Related Questions