Styling the Action Bar in Android can frequently seem difficult, if not impossible. It’s easy to do wrong and hard to do right. However, customizing the Action Bar title with a custom typeface is a surprisingly easy way to spruce up your app design.
There are several posts on Stack Overflow that recommend accomplishing this by leveraging the Action Bar’s custom view feature, or by getting a reference to the title TextView. These solutions are adequate but can lead to infuriating edge cases. We can do better.
You might have come across the
TypefaceSpan class, which allows you to style a section of text in a
TextView with a monospace or serif font. This is almost what we want to do, but we need to be able to provide our own
Here’s what a custom
TypefaceSpan might look like in use:
SpannableString s = new SpannableString("My Title"); s.setSpan(new TypefaceSpan(this, "MyTypeface.otf"), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // Update the action bar title with the TypefaceSpan instance ActionBar actionBar = getActionBar(); actionBar.setTitle(s);
Notice that we simply create a
SpannableString with our desired Action Bar title. We then create a new instance of our custom
TypefaceSpan providing it with our Activity context and the typeface name as arguments (so it can load the typeface from our application’s assets directory). The span is set on the entire length of the title (
... 0, s.length(), ...). Finally, we pass in the
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE flag, which simply indicates that the span should be removed if all of the spanned text is deleted. Here’s what the result might look like:
But what does the custom
TypefaceSpan implementation look like? Well, it’s surprisingly simple. I’ve created an example you can use in your own apps. You can get it at gist.github.com/twaddington/b91341ea5615698b53b8. Simply copy this class into your application and use it like I’ve indicated above. You can even subclass the custom
TypefaceSpan to add additional styles like colors or text shadows.