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.
String a = tv. getText(). toString(); int A = Integer. parseInt(a);
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.
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With