TextDrawable to display emojis and Unicode characters in Android
The best way to add emojis and graphics to your app without bundling graphics is to use Unicode characters. Unfortunately, setting these as drawables can be rather tricky.
Last week, I talked with a few people about the possibility of using TextDrawable to add a fixed prefix to an EditText. There are unfortunately a few different challenges. Which made this difficult for me:
- Cannot be done with XML’s (there is some literature about it, but a few objects I needed were private and I couldn’t get hold of them.
- Since we can’t create this in XML or set it as a compound drawable or background in XML, we get no preview in the editor.
- Drawable would have to be passed a paint object.
- Aligning the text to the text in the TextView/EditText would be tricky.
Well, this wasn't as hard as I thought it would have been. As a matter of fact it worked out rather nicely. Not only can you use it as a compound drawable, you can set it as a background as well. I've also implement the ability to ask it to resize the text drawn to fill a TextView’s background.
Why do I need a TextDrawable
Possible use cases for an EditText can be:
- Show a prefix on EditText that can’t be editable.
- Show a character counter on right or left drawables position.
- Show indication using uni-code characters that input is, short, long, correct or incorrect in an EditText.
- Use to to show an ellipsis on a single line EditText if the text is long as an indicator that there is something off screen. If you want to know more about this, ping me and I’ll give you an example.
Most of the above is possible with an images or by stacking Views together, this is hopefully a cleaner solution if Unicode characters and text are good enough (and why won’t this be ☺).
Show me a demo
Its worth pointing out that since the drawable reserves its space when set as a compound drawable (left, right, top or bottom) that changing the text in this scenario doesn't work as expected.
Just look at the demo below. The +61 and the ★ that you see in the EditText are drawn there with the TextDrawable. The ☺ that you see is also done with a TextDrawable, set as the background of a TextView, it is then being updated using a count down timer. As you can see, it can resize the text to ensure that it fits in the View’s width which is 200dp.
The code is on gist.
In order to build great Android apps, read more of my articles.