Nandha Nandha - 6 months ago 136
Java Question

How to get line count of textview before rendering?

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.

Answer
Rect bounds = new Rect();
Paint paint = new Paint();
paint.setTextSize(currentSize);
paint.getTextBounds(testString, 0, testString.length(), bounds);

int width = (int) Math.ceil((float) bounds.width() / currentSize);

Now devide the width of text with the width of your TextView and get the total lines.