Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically create TextView with ellipsis

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.

like image 413
sgarman Avatar asked Nov 10 '11 22:11

sgarman


1 Answers

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);
like image 55
stefan Avatar answered Oct 29 '22 10:10

stefan