如何在Android TextView中使用自定义省略号

jmh*_*let 9 android ellipsis textview

我有一个maxlines = 3的TextView,我想使用自己的省略号,而不是

"Lore ipsum ..."
Run Code Online (Sandbox Code Playgroud)

我需要

"Lore ipsum ... [See more]"
Run Code Online (Sandbox Code Playgroud)

为了给用户一个线索,点击视图将扩展全文.

可能吗 ?

我正在考虑检查TextView是否有省略号,并且在这种情况下添加文本"[查看更多]"并在之后设置省略号,但我找不到这样做的方法.

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

jmh*_*let 7

我终于以这种方式管理它(可能不是最好的):

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;
}
Run Code Online (Sandbox Code Playgroud)

  • textView.getLayout()返回null (5认同)
  • 而不是使用像`ellipsis ="..."中的三个点;`你应该使用HORIZONTAL ELLIPSIS字符(… entity - >```) (2认同)
  • Android使用`TextUtils.ELLIPSIS_NORMAL [0]`作为标准省略号,解析为''\ u2026'.这可以在[Layout#getEllipsisChar]中找到(https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/text/Layout.java#1835) TextView间接使用的方法. (2认同)