Search code examples
androidandroid-layouttextutils

Proper use for TextUtils.commaEllipsize


I'm looking for some sample code on how to use this correctly with a TextView.

the only thing I found in my Google searching was this test unit for the TextUtils class.

some guidance will be much appreciated.

EDIT:

I looked over the answer I got here and tried to implement it on my code. I used this code snippet:

    TextView title = (TextView) view.findViewById(R.id.listitemThreadsTitle);
    title.setVisibility(View.VISIBLE);

    TextPaint p = title.getPaint();
    String strTitle = "Moe, Joe, Isaac, Bethany, Cornelius, Charlie";
    title.setText(strTitle);
    float avail = p.measureText(strTitle);
    CharSequence ch = TextUtils.commaEllipsize(strTitle, p, avail, "one more", "%d more");
    title.setText(ch);

but the result was absolutely not what it's supposed to be.

it was more like: Moe, Joe, Isaac, Betha...

instead of: Moe, Joe, Isaac + 3


Solution

  • public static CharSequence commaEllipsize (CharSequence text, TextPaint p, 
                                           float avail, String oneMore, String more)
    

    Parameters:

    text - the text to truncate
    p - the Paint with which to measure the text
    avail - the horizontal width available for the text
    oneMore - the string for "1 more" in the current locale
    more - the string for "%d more" in the current locale

    Example Usage:

    String text = "Apple, Orange, Mango, Banana";
    TextView tv = new TextView(context);
    float textWidth = tv.getPaint().measureText(text );
    String tempStr = TextUtils.commaEllipsize(text, tv.getPaint(), textWidth, 
                                               "1 more", "%d more");
    tv.setText(tempStr);
    

    Update:

    TextView title = (TextView) view.findViewById(R.id.listitemThreadsTitle);
    title.setVisibility(View.VISIBLE);
    
    TextPaint p = title.getPaint();
    String strTitle = "Moe, Joe, Isaac, Bethany, Cornelius, Charlie";
    title.setText(strTitle);
    float avail = title.getMeasuredWidth();
    CharSequence ch = TextUtils.commaEllipsize(strTitle, p, avail, "one more", "%d more");
    title.setText(ch);