Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the text at a specific line in a TextView

I have a TextView that is X lines long. How do I get the text that is at, say, line 3?

Example: I have this TextView

This is line 1

And this is line 2

And this is line 3

I want to be able to get the String at any one of these lines by itself, such as getting the String at line 3 would return "And this is line 3". Searching for line breaks is not the solution I need, as it doesn't take into account text wrapping.

like image 463
Jason Robinson Avatar asked Jun 07 '11 23:06

Jason Robinson


People also ask

How do I get TextView text?

String a = tv. getText(). toString(); int A = Integer. parseInt(a);

How do I limit text in TextView?

you can extend the TextView class and overwrite the setText() function. In this function you check for text length or word cound. Better than counting the text length or the word cound a better way would be to use the "maxLines" attribute along with "ellipsize" attribute to attain the desired effect.

How do I assign text to TextView?

Set The Text of The TextView You can set the text to be displayed in the TextView either when declaring it in your layout file, or by using its setText() method. The text is set via the android:text attribute. You can either set the text as attribute value directly, or reference a text defined in the strings.


2 Answers

You can use textView.getLayout().getLineStart(int line) and getLineEnd to find the character offsets in the text.

Then you can just use textView.getText().substring(start, end) -- or subsequence if you are using Spannables for formatting/etc.

like image 64
Christopher Souvey Avatar answered Sep 21 '22 11:09

Christopher Souvey


Here is some code to supplement the accepted answer:

List<CharSequence> lines = new ArrayList<>(); int count = textView.getLineCount(); for (int line = 0; line < count; line++) {     int start = textView.getLayout().getLineStart(line);     int end = textView.getLayout().getLineEnd(line);     CharSequence substring = textView.getText().subSequence(start, end);     lines.add(substring); } 
like image 36
Suragch Avatar answered Sep 22 '22 11:09

Suragch