【问题标题】:How to change the ellipsis string of Android TextView?(... to ...more)如何更改 Android TextView 的省略号字符串?(... to ...more)
【发布时间】:2016-05-31 06:56:26
【问题描述】:

我想将省略号字符串从 ... 更改为自定义字符串,例如 abc...[more]。 但是在TextUtil中,省略号字符串是固定的:

private static final String ELLIPSIS_STRING = new String(ELLIPSIS_NORMAL);

【问题讨论】:

    标签: android textview


    【解决方案1】:

    我很惊讶还没有任何好的解决方案,所以我花了一些时间编写了自己的自定义 TextView,它允许您显示自定义省略号。在开发它时我想到的几件事:

    1. TextView 不应多次绘制文本,因为这是一项繁重的操作,可能会影响性能。
    2. 它应该尊重跨区字符串。
    3. 支持省略号的自定义文本颜色。

    如果您发现任何问题,请查看并告诉我:https://github.com/TheCodeYard/EllipsizedTextView

    这是一个截图:

    【讨论】:

      【解决方案2】:

      我在How to use custom ellipsis in Android TextView 找到了答案。但是必须在布局后运行该函数,可以在 OnGlobalLayoutListener.onGlobalLayout() 或 view.post() 上运行。

      【讨论】:

        【解决方案3】:

        试试这个方法

         public  void CustomEllipsize(final TextView tv, final int maxLine, final String ellipsizetext) {
        
            if (tv.getTag() == null) {
                tv.setTag(tv.getText());
            }
            ViewTreeObserver vto = tv.getViewTreeObserver();
            vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        
                @SuppressWarnings("deprecation")
                @Override
                public void onGlobalLayout() {
        
                    ViewTreeObserver obs = tv.getViewTreeObserver();
                    obs.removeGlobalOnLayoutListener(this);
                    if ((maxLine+1) <= 0) {
                        int lineEndIndex = tv.getLayout().getLineEnd(0);
                        String text = tv.getText().subSequence(0, lineEndIndex - ellipsizetext.length()) + " " + ellipsizetext;
                        tv.setText(text);
                    } else if (tv.getLineCount() >= (maxLine+1)) {
                        int lineEndIndex = tv.getLayout().getLineEnd((maxLine+1) - 1);
                        String text = tv.getText().subSequence(0, lineEndIndex - ellipsizetext.length()) + " " + ellipsizetext;
                        tv.setText(text);
                    }
                }
            });
        
        }
        

        并像这样使用这种方法

            final TextView txtView = (TextView) findViewById(R.id.txt);
            String dummyText = "sdgsdafdsfsdfgdsfgdfgdfgsfgfdgfdgfdgfdgfdgdfgsfdgsfdgfdsdfsdfsdf";
            txtView.setText(dummyText);
            CustomEllipsize(txtView, 2, "...[more]");
        

        【讨论】:

        • 不管需要与否,都会在最大行中省略。
        猜你喜欢
        • 2013-09-15
        • 2019-07-24
        • 2014-11-21
        • 2021-10-24
        • 1970-01-01
        • 2017-06-23
        • 2019-04-20
        • 2010-10-11
        • 1970-01-01
        相关资源
        最近更新 更多