22

how to get how many lines are displayed in visible part of TextView? I use text, which not fully placed in TextView on every screen resolution.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/logs_text"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</LinearLayout>

String s = "very big text"
TextView logText = (TextView) view.findViewById(R.id.logs_text);
logText.setText(s);     
mmBs
  • 8,421
  • 6
  • 38
  • 46
umni4ek
  • 365
  • 1
  • 2
  • 16
  • do you want to set how many lines the textview will have, or just get how many lines does he have? – Giacomoni Jan 31 '14 at 13:25
  • rephrased the question – umni4ek Jan 31 '14 at 13:36
  • use textviewobject.getText() to get the text set on textview and compare with original text. – Meenal Jan 31 '14 at 13:38
  • I someone is googling it to just limit number of lines in TextView then it's enough to set *maxLines* and *ellipsize* properties of the TextView: for example `android:maxLines="2" android:ellipsize="end"` – Boris Treukhov Nov 27 '15 at 14:43
  • Possible duplicate of [Is there a way of retrieving a TextView's visible line count or range?](http://stackoverflow.com/questions/2239356/is-there-a-way-of-retrieving-a-textviews-visible-line-count-or-range) – Raut Darpan Apr 11 '17 at 13:28

1 Answers1

26

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?

Community
  • 1
  • 1
Yaroslav Mytkalyk
  • 16,950
  • 10
  • 72
  • 99