Reputation: 14505
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
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
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
Reputation: 3992
String text = (String) textView.getText().subSequence(textView.getLayout().getEllipsisStart(0), textView.getText().length());
Upvotes: 10