How can I get the number of lines a string will take up in a TextView
before it is rendered.
A ViewTreeObserver
will not work because those are only fired after it is rendered.
How can I get the number of lines a string will take up in a TextView
before it is rendered.
A ViewTreeObserver
will not work because those are only fired after it is rendered.
Reference: Getting height of text view before rendering to layout
Get line of TextView before rendering.
This is my code base the link above. It's working for me.
Note: This code also must be set for real textview on screen
Now divide the width of text with the width of your TextView to get the total number of lines.
The accepted answer doesn't work when a whole word is placed on the next line in order to avoid breaking the word:
The only way to be 100% sure about the number of lines is to use the same text flow engine that TextView uses. Since TextView doesn't share its re-flow logic here's a custom string processor which splits text into multiple lines each of which fits the given width. It also does its best to not break the words unless the whole word does not fit:
Here's a part of a unit test:
Now one can be 100% sure about the line count in TextView without a need to render it:
You should use the new TextViewCompat to resize text. Include support libs version 26.
in your build.gradle:
In your activity:
If you know or can determine the width of the TextView's parent, you are able to invoke a view measurement which results in line count being calculated.
The TextView's
layout
is no longer null and you can check the calculated line count withmyTextView.lineCount
.