4

I want to change the ellipsis string from ... to custom string, such as ...[more]. But in TextUtil, the ellipsis string is fixed:

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

Then how to change the ellipses?

Sambhav Khandelwal
  • 3,585
  • 2
  • 7
  • 38
Neo lee
  • 71
  • 1
  • 6

3 Answers3

8

I was surprised that there isn't any good solution to that yet, so I spent sometime and wrote my own custom TextView which allows you to show a custom ellipsis. Few things I had in mind while developing it:

  1. The TextView shouldn't draw the text more than once since this is a heavy operation and could compromise the performance.
  2. It should respect Spanned strings.
  3. Support custom text color for the ellipsis.

Have a look and let me know if you find any issues: https://github.com/TheCodeYard/EllipsizedTextView

And here's a screenshot:

enter image description here

Georgios
  • 4,764
  • 35
  • 48
  • Thx for the lib! However, some issues. First, if the text content the default ellipsis, the ellipsis will be added at wrong position. Then, the lib use the `TextUtils.Ellipse()` which can give longer text, than the one displayed in the layout (when display on multiple lines). – Loïc Dumas Mar 29 '23 at 16:24
1

I found the answer in How to use custom ellipsis in Android TextView. But you must run the function after layout, you can run it on OnGlobalLayoutListener.onGlobalLayout() or view.post().

Community
  • 1
  • 1
Neo lee
  • 71
  • 1
  • 6
0

Try This Method

 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);
            }
        }
    });

}

and use this method like this

    final TextView txtView = (TextView) findViewById(R.id.txt);
    String dummyText = "sdgsdafdsfsdfgdsfgdfgdfgsfgfdgfdgfdgfdgfdgdfgsfdgsfdgfdsdfsdfsdf";
    txtView.setText(dummyText);
    CustomEllipsize(txtView, 2, "...[more]");
Abhishek Patel
  • 4,280
  • 1
  • 24
  • 38