Defining and Using Styles

Android offers styles and themes, filling the same sort of role that CSS does in Web development. We have seen a little bit about themes, such as having a custom theme that defines the core colors to be used by your app.

On the whole, styles and themes are powerful yet confusing tools in the Android developer’s toolbox. The “confusing” aspect stems from documentation that has ranged from “simply not existing” to “limited and mystifying” over the years. As such, most Android app development seems to avoid styles and themes to the extent possible, settling instead for directly configuring widgets in layout files. This works, and for smaller projects it is perfectly reasonable. The larger the project, the greater the likelihood is that you will benefit from using styles and themes, just as a larger Web app is more likely than a smaller one to benefit from a well-designed set of CSS stylesheets.

In this chapter, we will take a slightly “deeper dive” into styles and themes, exploring how you can create your own and apply them to your app’s UI.

Styles: DIY DRY

The purpose of styles is to encapsulate a set of attributes that you intend to use repeatedly, conditionally, or otherwise wish to keep separate from your layouts. The primary use case is “don’t repeat yourself” (DRY) — if you have a bunch of widgets that look the same, use a style to use a single definition for “look the same”, rather than copying the look from widget to widget.

The CustomStyle sample module in the Sampler and SamplerJ projects is based off of the previous InstanceState sample, where we are showing a list of lifecycle events. In this edition of the sample, we will define and apply a style resource to some of the TextView widgets in the list rows.

Styles and themes are defined using a style resource. By convention, style resources go in res/values/styles.xml, though the actual filename does not matter, so long as it is in a values resource directory.

Our res/values/styles.xml defines two style resources. One, AppTheme, is our custom application theme, and we will revisit it later in the chapter.

The other is CustomText:

  <style name="CustomText">
    <item name="android:textColor">?colorAccent</item>
    <item name="android:textStyle">italic</item>
    <item name="android:fontFamily">monospace</item>
  </style>

In the next sections, we will explore more about what this style does and how we are using it.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.