如何在 Android TextView 中使用自定义省略号 [英] How to use custom ellipsis in Android TextView
问题描述
我有一个 maxlines=3 的 TextView,我想使用我自己的省略号,而不是
I have a TextView with maxlines=3 and I would like to use my own ellipsis, instead of
"Lore ipsum ..."
我需要
"Lore ipsum ... [See more]"
为了给用户一个提示,点击视图会展开全文.
in order to give the user a clue that clicking on the view is going to expand the full text.
有可能吗?
我正在考虑检查 TextView 是否有省略号,在这种情况下添加文本[查看更多]",然后在之前设置省略号,但我找不到这样做的方法.
I was thinking about check whether TextView has ellipsis and in such a case add the text "[See more]" and after that set ellipsis just before, but I couldn't find the way to do that.
也许如果我找到文本被剪切的位置,我可以禁用省略号并创建一个子字符串,然后添加... [查看更多]",但我不知道如何获得该位置.
Maybe if I find the position where the text is cutted, I can disable the ellipsis and make a substring and later add "... [See more]", but again I dont know how to get that position.
推荐答案
我终于这样管理了(可能不是最好的):
I've finally managed it in this way (may be not the best one):
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;
}
这篇关于如何在 Android TextView 中使用自定义省略号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!