If a String is longer than the TextView's width it automatically wraps onto the next line. I can avoid this by using android:singleLine
(deprecated) or by setting android:inputType="text"
. What I now need is something that replaces the last 3 characters of my String with "...". Since I'm not using a monospace font this will always be different depending on the letters used in my String. So I'm wondering what's the best way to get the last 3 characters of a String in a TextView and replace them. Maybe there's already something implemented in the Android framework, since this must me a common problem.
views:
1563answers:
2
+1
A:
Don't know much about Android, but I'd start with apache commons lang
Abbreviates a String using ellipses. This will turn "Now is the time for all good men" into "Now is the time for..." Specifically: * If str is less than maxWidth characters long, return it. * Else abbreviate it to (substring(str, 0, max-3) + "..."). * If maxWidth is less than 4, throw an IllegalArgumentException. * In no case will it return a String of length greater than maxWidth. StringUtils.abbreviate(null, *) = null StringUtils.abbreviate("", 4) = "" StringUtils.abbreviate("abcdefg", 6) = "abc..." StringUtils.abbreviate("abcdefg", 7) = "abcdefg" StringUtils.abbreviate("abcdefg", 8) = "abcdefg" StringUtils.abbreviate("abcdefg", 4) = "a..." StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
Duncan McGregor
2009-11-03 11:57:33
Thats based on the number of characters and not of the actual width of the string. Doesn't look very nice.
OneWorld
2010-09-22 12:01:38
+10
A:
You should be able to use the "ellipsize" property of a text view:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/text_mytext"
android:ellipsize="end"
android:singleLine="true"
/>
You may also need to apply gravity values to the layout too; I have sometimes seen "auto-stretching" views without them.
Nate
2009-11-03 13:28:27
Perfect. Thanks. I have tried that before, but didn't work, because I used android:inputType="text" instead of android:singleLine="true" (which is supposed to be deprecated). But now I'm gonna stick with android:singleLine="true". Muchas gracias.
znq
2009-11-03 14:08:34
It still doesn't add the "...". For me, this question is not fully answered! This answer will make "short verylongword" to just "short" and not "short verylon..." On top of that you guys suggest using a deprecated attribute.
OneWorld
2010-09-22 12:06:30