【问题标题】:TextView: Add text after ellipsis or change ellipsis characterTextView:在省略号后添加文本或更改省略号字符
【发布时间】:2013-09-15 07:01:03
【问题描述】:

我要做什么

我正在尝试使用 TextView

android:ellipsize="end"
android:maxLines="3"

最后用“... Show More”代替“...”。

我在哪里

如果 TextView 是单行,这将很容易,因为我可以使用 2 个 TextView,但我需要它有多行,并且“显示更多”需要内联。

我一直在寻找一种方法来更改最后添加的省略号但找不到任何东西。

我能想到的唯一解决方案是放弃自动省略号,测量文本并从代码中添加“...显示更多”。

问题

有没有办法用自定义的东西替换 Android 在末尾添加的内容(“...”)?

【问题讨论】:

  • 检查我发布你的答案。

标签: android textview ellipsis


【解决方案1】:

试试这个方法

创建这个函数

public  void makeTextViewResizable(final TextView tv, final int maxLine, final String expandText) {

        if (tv.getTag() == null) {
            tv.setTag(tv.getText());
        }
        ViewTreeObserver vto = tv.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @SuppressWarnings("deprecation")
            @Override
            public void onGlobalLayout() {

                ViewTreeObserver obs = tv.getViewTreeObserver();
                obs.removeGlobalOnLayoutListener(this);
                if (maxLine <= 0) {
                    int lineEndIndex = tv.getLayout().getLineEnd(0);
                    String text = tv.getText().subSequence(0, lineEndIndex - expandText.length() + 1) + " " + expandText;
                    tv.setText(text);
                } else if (tv.getLineCount() >= maxLine) {
                    int lineEndIndex = tv.getLayout().getLineEnd(maxLine - 1);
                    String text = tv.getText().subSequence(0, lineEndIndex - expandText.length() + 1) + " " + expandText;
                    tv.setText(text);
                }
            }
        });

    }

如何使用

这将在第 4 行末尾写“SeeMore”而不是“...”

makeTextViewResizable(tv, 4, "SeeMore");

现在不需要在xml中写这些行

android:ellipsize="end"
android:maxLines="3"

【讨论】:

  • 感谢您的回答。在寻找解决方案后,我发现 Android ellipsize 不适用于多行(已知的旧错误 link)。我最终使用了一种解决方案来解决这个问题,并对其进行了修改以满足我的需要。
  • 我将其标记为已接受的答案,因为它解决了问题,但对于登陆此页面的其他人:该解决方案不适用于具有跨度的文本(例如,如果您使用 Html.fromHtml ) 如果文本在 ListView 中,您可能会得到不稳定的结果。
  • 根据您的代码,我们可以稍微修改一下以满足我们的期望。非常感谢!
  • 设置标签的目的是什么?