如何更改Android TextView的省略号字符串?(...到...更多)

时间:2016-05-31 06:56:26

标签: android textview

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

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

3 个答案:

答案 0 :(得分:2)

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

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

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

这是屏幕截图:

enter image description here

答案 1 :(得分:1)

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

答案 2 :(得分:0)

尝试此方法

 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]");