Ellipsize TextView at end of word

I use the attribute in TextView

android:ellipsize

conjunction with android:maxLines

to make the text fit on a maximum of three lines.

The problem is that sometimes the text is cut in the middle of the word. I would like to ellipse the text only at the end of a word. For example:.

Android is awesome

It now looks like this:

Android is awe ...

But I would like it to look like this:

Android ...

Also, the user can change dynamically textSize

in this TextView

, so it is quite difficult to predict which word will be the last.

Is there a way to ellipse ONLY at the end of a full word? If the system doesn't allow this, is there a library that will provide this functionality, or the only way to write my own class that does this?

+3


source to share


1 answer


You must put an ellipsis at the end for the text representation. Then after setting the text, add a globallayout listener to the textview and change its text as follows:



TextView articleTitle = (TextView) v.findViewById(R.id.articleTitle);
        articleTitle.setText("This is a big big text");
        doEllipse(articleTitle);




 public void doEllipse(final TextView tv) {
    tv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
           tv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
           String text = tv.getLayout().getText().toString();
           int text1Index = text.indexOf("…");
           if (text1Index > 0) {
               text = text.substring(0, text.lastIndexOf(" ")) + "...";
               tv.setText(text);
           }    
        }
    });

}

      

-1


source







All Articles