2014-09-26 56 views
3

我有一个TextView用的maxlines = 3,我想用我自己的省略号,而不是如何使用自定义的省略号Android中的TextView

"Lore ipsum ..." 

我需要

"Lore ipsum ... [See more]" 

以给用户一个线索,点击视图将扩展全文。

可能吗?

我在考虑检查TextView是否有省略号,并在这种情况下添加文本“[查看更多]”之后,之前设置省略号,但我找不到方法来做到这一点。

也许如果我找到文本被切割的位置,我可以禁用省略号并创建子字符串,然后添加“... [查看更多]”,但我不知道如何获得该位置。

+0

参考'l.getEllipsisStart()' – 2014-09-26 08:12:34

回答

3

我终于设法它以这种方式(可能不是最好的一个):

private void setLabelAfterEllipsis(TextView textView, int labelId, int maxLines){ 

    if(textView.getLayout().getEllipsisCount(maxLines-1)==0) { 
     return; // Nothing to do 
    } 

    int start = textView.getLayout().getLineStart(0); 
    int end = textView.getLayout().getLineEnd(textView.getLineCount() - 1); 
    String displayed = textView.getText().toString().substring(start, end); 
    int displayedWidth = getTextWidth(displayed, textView.getTextSize()); 

    String strLabel = textView.getContext().getResources().getString(labelId); 
    String ellipsis = "..."; 
    String suffix = ellipsis + strLabel; 

    int textWidth; 
    String newText = displayed; 
    textWidth = getTextWidth(newText + suffix, textView.getTextSize()); 

    while(textWidth>displayedWidth){ 
     newText = newText.substring(0, newText.length()-1).trim(); 
     textWidth = getTextWidth(newText + suffix, textView.getTextSize()); 
    } 

    textView.setText(newText + suffix); 
} 

private int getTextWidth(String text, float textSize){ 
    Rect bounds = new Rect(); 
    Paint paint = new Paint(); 
    paint.setTextSize(textSize); 
    paint.getTextBounds(text, 0, text.length(), bounds); 

    int width = (int) Math.ceil(bounds.width()); 
    return width; 
} 
+1

,而不是使用三个点像'省略号=”。 ..“;'你应该使用水平ELLIPSIS字符(…实体 - >'...') – 2014-09-29 11:46:42

+0

Thx!我会用它! – jmhostalet 2014-09-29 13:51:21

+5

textView.getLayout()返回null – 2015-06-17 07:48:22

相关问题