The TextUtils classs has as method called ellipsize
public static CharSequence ellipsize (CharSequence text, TextPaint p, float avail, TextUtils.TruncateAt where)
Added in API level 1
Returns the original text if it fits in the specified width given the properties of the specified Paint, or, if it does not fit, a truncated copy with ellipsis character added at the specified edge or center.
Here is how we can use it. Lets assume "Title of the item - (5 items)" is fullText, (5 items) is suffix, textView is your text view containing the text.
String ellipsizedText = TextUtils.ellipsize(fullText, textView.getPaint(), fullTexViewtWidth ,TextUtils.TruncateAt.END);
Now either the text will be ellipsized or it won't. We can check this by checking for the presence of suffix in the ellipsizedText.
If it is ellipsized (suffix is removed), we should call the ellipsize function again but this time with reduced width since we want to preserve a space for our suffix string and remove suffix since we are adding it separately. So, the new call will be
ellipsizedText = TextUtils.ellipsize(removedSuffixText, textView.getPaint(), reducedWidth ,TextUtils.TruncateAt.END);
finally we set the text of the textView as ellipsizedText+suffix;
Few values we need to find out
- fullTexViewtWidth - This can be tricky since we have not specified specific width for the text view. suppose we set the width as match parent then we can achieve it via view tree observer. Follow the answers here
reducedWidth - This is even more tricky. To calculate this we need to find the width occupied by suffix and subtract it from fullTexViewtWidth. This answer explains how to find width occupied by suffix
final float densityMultiplier = getContext().getResources().getDisplayMetrics().density;
final float scaledPx = 20 * densityMultiplier;
paint.setTextSize(scaledPx);
final float size = paint.measureText("sample text");
I am afraid this will only work when maxLines is 1 and width is set to matchparent for textView.