How to Get Number of Lines of Textview

How to determine the number of lines visible in TextView?

android.text.Layout contains this information and more. Use textView.getLayout().getLineCount() to obtain line count.

Be wary that getLayout() might return null if called before the layout process finishes. Call getLayout() after onGlobalLayout() or onPreDraw() of ViewTreeObserver. E.g.

textView.getViewTreeObserver().addOnPreDrawListener(() -> {
final int lineCount = textView.getLayout().getLineCount();
});

If you want only visible line count you should probably use the approach mentioned in the answer below:

Is there a way of retrieving a TextView's visible line count or range?

How to get line count of textview before rendering?

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

Now divide the width of text with the width of your TextView to get the total number of lines.

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

currentSize : Expected size of the view in which the text will be rendered. The size should not go beyond the screen width.

How to Check the number of lines in a String in Android?

Use a thread to count the number of lines,

 textView.setText("Text Here");
textView.post(new Runnable() {

@Override
public void run() {

Log.v("Line count: ", textView.getLineCount()+"");
}
});

If you want to limit the number of lines in TextView from xml then use android:maxLines

Android TextView and getting line of text

If I understand correctly the answer to question 2 is:

textView.getLineBounds (int line, Rect bounds)

The width in pixels should be abs(bounds.right - bounds.left); and the height is abs(bounds.bottom - bounds.top)

Your first question is a bit more tricky, but something like this should do the required magic:

Layout layout = textView.getLayout();
String text = textView.getText().toString();
int start=0;
int end;
for (int i=0; i<textView.getLineCount(); i++) {
end = layout.getLineEnd(i);
line[i] = text.substring(start,end);
start = end;
}


Related Topics



Leave a reply



Submit