Android: TextView automatically truncate and replace last 3 char of String
Secure a quick win by using this method to truncate and append "..." to a String
in a TextView
.
Assign the snipped String to your TextView
:
Here truncateEnd
chisels off the last 3 characters of a hefty String
and smartly glues ...
to the end, if and only if the String
is heavier than 3 characters.
XML-driven truncation
For a purely XML-based truncation setup, adjust the TextView
attributes as follows:
The nifty collection of attributes render your TextView
into a certified truncation expert, eliminating the tail and jumping in an ellipsis "..."
, all without a single line of code.
Piecing it together: Code embraced
Should your heart lean towards crafting a programmatically seasoned solution:
Simultaneously elegantly straightforward and yet neatly powerful, these code lines charge your TextView
with the diligence of enforcing single-line display at runtime and a straight-to-the-point ellipsizing behaviour.
Monospace font and Truncation: A Love Story
When working with monospace fonts, every character is a perfect square in a grid. Knowing when truncation will occur is like seeing through a crystal ball:
- Got code snippets or logs? A monospace font makes them look like a printout from 1973.
- The IKEA instruction manual of text layouts: strict character limits.
- If you like military parades, have we got the font for you! Monospace fonts ensure every character occupies the same space, making your UI look uniformly awesome.
Taking on the World: RTL and Special Characters
Who says ellipsis can't play nice with other languages? Here's what you should know:
- Those Arabic and Hebrew buds write from right to left (RTL), but
TextView
has got their backs. - Got friends who like to express themselves with emojis? Or perhaps fancy some Asian characters? Some of them might hog a bit more space, so watch out for your ellipsis!
Accessibility: Not just a buzzword
When it comes to accessibility, remember these points:
- Always ensure your truncation is just for show, and not affecting how the text is read by assistive technology. You might trim the visualization, but never the meaning!
- If the full text is needed, remember you can use content-description properties to be the hero the users need.
Was this article helpful?