ademar111190
ademar111190

Reputation: 14505

How to get the ellipsized text in a TextView

How do I get the text that has been truncated by Android into an ellipsis?

I have a textview:

<TextView
    android:layout_width="120dp"
    android:layout_height="wrap_content"
    android:ellipsize="end"
    android:singleLine="true"
    android:text="Um longo texto aqui de exemplo" />

On a device this TextView is shown like this:

"Um longo texto a..."

How do I get the rest of the text?

I am looking for something like getRestOfTruncate() which would return "qui de exemplo".

Upvotes: 12

Views: 8893

Answers (3)

V. Gerasimenko
V. Gerasimenko

Reputation: 229

My solution. Kotlin extension function:

fun TextView.getEllipsizedText(): String {
if (text.isNullOrEmpty()) return ""
return layout?.let {
    val end = textContent.text.length - textContent.layout.getEllipsisCount(maxLines - 1)
    return text.toString().substring(0, end)
} ?: ""
}

Upvotes: 3

Gil SH
Gil SH

Reputation: 3868

Using textView.getLayout().getEllipsisStart(0) only works if android:singleLine="true"

Here is a solution that will work if android:maxLines is set:

public static String getEllipsisText(TextView textView) {
    // test that we have a textview and it has text
    if (textView==null || TextUtils.isEmpty(textView.getText())) return null;
    Layout l = textView.getLayout();
    if (l!=null) {
        // find the last visible position
        int end = l.getLineEnd(textView.getMaxLines()-1);
        // get only the text after that position
        return textView.getText().toString().substring(end);
    }

    return null;
}

Remember: this works after the view is already visible.

Usage:

textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            Log.i("test" ,"EllipsisText="+getEllipsisText(textView));
        }
    });

Upvotes: 1

Sudar Nimalan
Sudar Nimalan

Reputation: 3992

String text = (String) textView.getText().subSequence(textView.getLayout().getEllipsisStart(0), textView.getText().length());

Upvotes: 10

Related Questions