检测 TextView 是否因为设置 ellipsize 属性而显示省略号

2,998 阅读1分钟

背景

对于 TextView,在实际开发中,由于内容的不确定性,有时候文本内容会很长,这时我们会使用 ellipsize 属性进行省略号设置,ellipsize 有5个取值 end,middle,marquee,none,start ,使用比较多的是 end,这样只要设置 TextView 的 maxLines 属性后,当文本长度超出最长限制后,就会在结尾显示省略号,如果你想让省略号显示在最中间,就需要设置 middle

问题

但是一些情况下,你需要在程序中检测这个 TextView 是否显示了省略号,比如超长显示后,给一个点击查看更多的 按钮之类的操作,那如何对 TextView 进行省略号检测呢?别说用

TextView.getText().toString().endWith("...")

这是肯定不行的。

解决办法

You can get the layout of the TextView and check the ellipsis count per line.

通过 TextView 实例拿到对应的 Layout,然后使用 Layout 的 getEllipsisCount 方法查询到指定行中省略号的次数,如果你的 TextView 是单行,直接查询第 0 行,具体代码如下:

Layout layout = textview.getLayout();
if (layout != null) {
    int lines = l.getLineCount();
    if (lines > 0)
        if (layout.getEllipsisCount(lines-1) > 0)
            Log.d(TAG, "Text is ellipsized");
}

Note:你在使用上面的方法时,应该确保 TextView 已经渲染成功,为此,你最好给上述代码包一层,如下

textview.post(new Runnable() {
            @Override
            public void run() {
                Layout l = tvAreaName.getLayout();
                if (l != null) {
                    if (l.getEllipsisCount(0) > 0){
                        Log.d(TAG, "Text is ellipsized");
                    }else{
                        Log.d(TAG, "Text is not ellipsized");
                    }
                }
            }
        });

Good Luck

参考链接

android - How do I tell if my textview has been ellipsized? - Stack Overflow

原文:检测 TextView 是否因为设置 ellipsize 属性而显示省略号 · Issue #9 · maoruibin/maoruibin.github.com