Programmatically create TextView with ellipsis
Asked Answered
F

2

43

I'm programmatically creating a TextView that I want to ellipsis at the end.

pseudo code:

    tv.setEllipsize(TextUtils.TruncateAt.END);
    tv.setHorizontallyScrolling(false);
    tv.setSingleLine();

The above works GREAT.

    tv.setEllipsize(TextUtils.TruncateAt.END);
    tv.setHorizontallyScrolling(false);
    tv.setMaxLines(1);

This does not work. Is this a bug? I don't understand why I can't get text to ellipses at the end when specifying maxLines especially a maxLine of 1 but setSingleLine is ok.

Fabiano answered 10/11, 2011 at 22:57 Comment(0)
E
84

setSingleLine() or setSingleLine(true) prevents the TextView from changing its height to more lines and forces the TextView to ignore line breaks (the symbol \n in a string).

setMaxLines(int n) displays the first n lines of the String displayed in the TextView which are separated by a line break.

For example let the String be "my first line \n and my second line \n and a third one"

  • setSingleLine() lets the TextView display "my first line and my.." since the display width is exceeded and
  • setMaxLines(1) results in "my first line"
  • setMaxLines(2) results in "my first line" and below a line saying "and my second line"
  • setMaxLines(3) obviously does not have any effect on this sample string.

Update: This should work for "setDoubleLine with truncation":

// optional: string.replace("\n",""); or string.replace("\n"," ");
tv.setSingleLine(false);
tv.setEllipsize(TextUtils.TruncateAt.END);
int n = 2; // the exact number of lines you want to display
tv.setLines(n);
Eohippus answered 10/11, 2011 at 23:12 Comment(2)
Awesome. Is it possible to have a TextView that is two lines and still ellipse at the end? ie, setDoubleLine() etc? This is how I imagined maxLine to work. For what it's worth my height and width are set to dip values, not match_parent.Fabiano
@AndreyButov thanks for suggesting an edit, I would have accepted if not asleep. I corrected the post now according to your suggestion. Thanks again.Eohippus
G
0

Java

textview.setMaxLines(maxLines); // set max lines to show
textView.setEllipsize(TextUtils.TruncateAt.END); // set ellipsize postion

Or Add TextView Attributes

XML

android:maxLines="1"
android:ellipsize="end"
Guesthouse answered 16/12, 2023 at 7:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.