Illustration by Virginia Poltrack

What’s your text’s appearance?

Understanding how to declaratively style text on Android.

When styling text in Android apps, TextView offers multiple attributes and different ways to apply them. You can set attributes directly in your layout, you can apply a style to a view, or a theme to a layout or perhaps set a text appearance. But which should you use? What happens if you combine them?

Which to use and when?

This article outlines the different approaches to declaratively styling text (i.e. when you inflate an XML layout), looking at their scope and precedence and when you should use each technique.

tl;dr;

You really should read the whole post but here’s a summary.

Be aware of the precedence order of different styling techniques — if you’re trying to style some text and not seeing the results you expect then your changes are likely being overridden by something higher up in this hierarchy:

The hierarchy of text styling techniques

I’d suggest this workflow for styling text:

  1. Set any app wide styling in a textViewStyle default style in your theme.
  2. Set up a (small) selection of TextAppearances your app will use (or use/extend from MaterialComponent’s styles) and reference these directly from your views
  3. Create styles setting any attributes not supported by TextAppearance (which themselves specify one of your TextAppearances).
  4. Perform any unique styling directly in your layout.

Show some style

While you can directly set TextView attributes in your layout, this approach can be tedious and error prone. Imagine trying to update the color of all text views in your app this way 🙀. As with all views, you can (and should!) instead use styles to promote consistency, reuse and enable easy updates. To this end, I’d recommend creating styles for text whenever you’re likely to want to apply the same styling to multiple views. This is extremely simple and largely handled by the Android view system.

What’s happening under the hood when you set a style on a view? If you’ve ever written a custom view, you’ve likely seen a call to context.obtainStyledAttributes(AttributeSet, int[], int, int). This is how the Android view system delivers the attributes specified in your layout to the view. The AttributeSet parameter can essentially be thought of as a map of the XML parameters you specify in your layout. If this AttributeSet specifies a style then the style is read first, then the attributes specified directly on the view are applied on top of that. In this way we arrive at our first rule of precedence.

View > Style

Attributes defined directly on a view always “‘win” and will override those specified in a style. Note that the combination of the style and view attributes are applied; defining an attribute on a view that also appears in the style doesn’t discard the entire style. It’s also interesting to note that there’s no real way in your views to determine where styling is coming from; it’s resolved by the view system for you in this single call. You can’t receive both and pick.

Whilst styles are extremely useful, they do have their limits. One of which is that you can only apply a single style to a view (unlike something like CSS on the web where you can apply multiple classes). TextView however, has a trick up its sleeve, it offers a TextAppearance attribute which functions similarly to a style. If you supply text styling via a TextAppearance that leaves the style attribute free for other styling which sounds useful. Let’s take a closer look at what TextAppearance is and how it works.

TextAppearance

There’s nothing magical about TextAppearance (like a secret mode to apply multiple styles that Android doesn’t want you to know about!!!1!), TextView does some very helpful legwork for you. Let’s peek at some of TextView’s constructor to see what’s going on.

TypedArray a = theme.obtainStyledAttributes(attrs, com.android.internal.R.styleable.TextViewAppearance, defStyleAttr, defStyleRes);
TypedArray appearance = null;
int ap = a.getResourceId(com.android.internal.R.styleable.TextViewAppearance_textAppearance, -1);
a.recycle();
if (ap != -1) {
appearance = theme.obtainStyledAttributes(ap, com.android.internal.R.styleable.TextAppearance);
}
if (appearance != null) {
readTextAppearance(context, appearance, attributes, false);
appearance.recycle();
}
// a little later
a = theme.obtainStyledAttributes(attrs, com.android.internal.R.styleable.TextView, defStyleAttr, defStyleRes);
readTextAppearance(context, a, attributes, true);

So what is happening here? Essentially TextView first looks if you’ve supplied android:textAppearance, if so it loads that style and applies any properties it specifies. Later on, it then loads all attributes of the view (which remember, includes the style) and applies them. We therefore arrive at our second precedence rule:

View > Style > TextAppearance

Because the text appearance is checked first, any attributes defined either directly on a view or in a style will override the text appearance.

There’s one other caveat to be aware of with TextAppearance which is that is supports a subset of styling attributes that TextView offers. To understand this, let’s go back to this line:

obtainStyledAttributes(ap, android.R.styleable.TextAppearance);

We’ve looked at the 4 arg version of obtainStyledAttributes, this 2 arg version is slightly different. It instead looks at a given style (as identified by the first id parameter) and filters it to only the attributes in this style which appear in the second attrs array param. As such the styleable android.R.styleable.TextAppearance defines the scope of what TextAppearance understands. Looking at the definition of this we can see that TextAppearance supports many but not all attributes that TextView supports.

<attr name="textColor" />
<attr name="textSize" />
<attr name="textStyle" />
<attr name="typeface" />
<attr name="fontFamily" />
<attr name="textColorHighlight" />
<attr name="textColorHint" />
<attr name="textColorLink" />
<attr name="textAllCaps" format="boolean" />
<attr name="shadowColor" format="color" />
<attr name="shadowDx" format="float" />
<attr name="shadowDy" format="float" />
<attr name="shadowRadius" format="float" />
<attr name="elegantTextHeight" format="boolean" />
<attr name="letterSpacing" format="float" />
<attr name="fontFeatureSettings" format="string" />

Styling attributes supported by TextAppearances

Some common TextView attributes not included are lineHeight[Multiplier|Extra], lines, breakStrategy & hyphenationFrequency. TextAppearance works at the character level, not paragraph so attributes affecting the whole layout are not supported.

So TextAppearance is very useful, it lets us define a style focused on text styling attributes and leaves a view’s style free for other uses. It does however have a limited scope and is at the bottom of the precedence chain, so be aware of its limitations.

Sensible defaults

When we took a look at how the Android view system resolved attributes (context.obtainStyledAttributes) we actually simplified things a little. This calls through to theme.obtainStyledAttributes (using the current Theme of the Context). Checking the reference this shows the precedence order we looked at before and specifies 2 more places it looks to resolve attributes: the view’s default style and the theme.

The styling precedence order from Theme documentation

We’ll come back to the theme but let’s take a look at default styles. What the heck is a default style? To answer this I think it’s illustrative to take a quick detour from TextView and look at the humble Button. When you drop a <Button> into your layout, it looks something like this.

A standard Button

Why? If you look at the source code to Button, it’s pretty sparse:

public class Button extends TextView {
  public Button(Context context) {
this(context, null);
}
  public Button(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.buttonStyle);
}
  public Button(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
  public Button(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
  @Override public CharSequence getAccessibilityClassName() {
return Button.class.getName();
}
  @Override public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
if (getPointerIcon() == null && isClickable() && isEnabled()) {
return PointerIcon.getSystemIcon(getContext(), PointerIcon.TYPE_HAND);
}
return super.onResolvePointerIcon(event, pointerIndex);
}
}

That’s it! The entire class (less comments). You can check here. I’ll wait. So where does the background, the capitalized text, the ripple etc all come from? You might have missed it, but it’s all in the 2 arg constructor; the one called when a layout is inflated from XML. It’s the last param which specifies a defaultStyleAttr of com.android.internal.R.attr.buttonStyle. This is the default style which is essentially a point of indirection allowing you to specify a, well, style to use by default. It doesn’t directly point to a style, but lets you point to one in your theme which it will check when resolving attributes. And that’s exactly what all themes you’d typically inherit from do to provide the default look and feel for common widgets. Looking at the Material theme for example, it defines <item name="buttonStyle">@style/Widget.Material.Light.Button</item> and it is this style which supplies all of the attributes, which theme.obtainStyledAttributes will deliver if you don’t specify anything else.

Going back to TextView, it also offers a default style: textViewStyle. This can be very handy if you want to apply some styling to each and every TextView in your app. Say you wanted to set a default line spacing multiplier of 1.2 throughout. You could do this through styles/TextAppearances and try to enforce this through code review (or perhaps even a fancy custom Lint rule) but you’d have to be vigilant and be sure to onboard new team members and be careful with refactors etc.

A better approach might be to specify your own default style for all TextViews in the app, encoding the desired behavior. You can do this by setting your own style for textViewStyle which extends from the platform or MaterialComponents/AppCompat default.

<style name="Theme.MyApp"
parent="@style/Theme.MaterialComponents.Light">
...
<item name="android:textViewStyle">@style/Widget.MyApp.TextView</item></style>
<style name="Widget.MyApp.TextView"
parent="@android:style/Widget.Material.TextView">
<item name="android:textAppearance">@style/TextAppearance.MyApp.Body</item>
<item name="android:lineSpacingMultiplier">@dimen/text_line_spacing</item>
</style>

So factoring this in, our precedence rules become:

View > Style > Default Style > TextAppearance

As part of the view systems attribute resolution, this slots in after styles (so anything in a default style is trumped by an applied style or view attribute) but still will override a text appearance. Default styles can be pretty handy. If you’re ever writing your own custom view then they can be a powerful way to implement default behavior while allowing easy customization.

If you’re subclassing a widget and not specifying your own default style then be sure to use the parent classes default style in your constructors (don’t just pass 0). For example, if you’re extending AppCompatTextView and write your own 2 arg constructor, be sure to pass android.R.attr.textViewStyle as the defaultStyleAttr (like this) otherwise you’ll lose the parent’s behavior.

Theme

As mentioned before, there’s one (final, I promise) way to provide styling information. The other place theme.obtainStyledAttributes will look is directly in the theme itself. That is if you supply a style attribute like android:textColor in your theme, the view system will pick this up as a last resort. Generally it’s a Bad Idea™ to mix theme attributes and style attributes i.e. something you’d apply directly to a view should generally never be set on a theme (and vice versa) but there are a couple of rare exceptions.

One example might be if you’re trying to change the font throughout your app. You could use one of the techniques above but manually setting up styles/text appearances everywhere would be repetitive and error prone and default styles only work at the widget level; subclasses might override this behavior e.g. buttons define their own android:buttonStyle which wouldn’t pick up your custom android:textViewStyle. Instead you could specify the font in your theme:

<style name="Theme.MyApp"
parent="@style/Theme.MaterialComponents.Light">
...
<item name="android:fontFamily">@font/space_mono</item>
</style>

Now any view which supports this attribute will pick this up unless overridden by something with higher precedence:

View > Style > Default Style > Theme > TextAppearance

Again, as this is part of the view styling system, it will override anything supplied in a text appearance, but be overridden by any more specific attributes.

Be mindful of this precedence. In our app-wide-font example you might expect Toolbars to pick up this font as they contain a title which is a TextView. The Toolbar class itself however defines a default style containing a titleTextAppearance which itself specifies android:fontFamily, and directly sets this on the title TextView, overriding the theme level value. Theme level styling can be useful, but is easily overridden so be sure to check that it’s applied as expected.

Bonus: Outspanding matters

This entire article has looked at declarative view level styling, that is how to style an entire TextView at inflation time. Any styling applied after inflation (e.g. textView.setTextColor(…)) will override the declarative styling. TextView also supports more fine grained styling via Spans. I won’t go into this subject as it’s thoroughly covered in these articles by Florina Muntenescu

I mention it for completeness to bear in mind that programmatic styling and spans would sit at the top of our precedence order:

Span > Setters > View > Style > Default Style > Theme > TextAppearance

Choose your style

While there are multiple ways of styling text, understanding the differences between the techniques and their limitations helps you to reach for the right tool for the job at hand or understand why one technique takes precedence over another.

Happy text styling!

Like what you read? Give Nick Butcher a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.