Styles and themes in Android
Today we will learn about styles and themes in Android.
A Style is a collection of properties that set the appearance of a single View or window. The idea behind styles is similar to CSS - you define styles of an object somewhere outside of the layout code and then just apply the style to one or multiple elements.
A Theme is a style that is applied to an entire Activity or all Activities of an application.
The process for creating styles and themes is the same.
Create a new XML style in res/values/ directory, you can use whatever name you want.
Add this code inside:
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="SpecialText" parent="@android:style/TextAppearance.Medium"> <item name="android:layout_width">fill_parent</item> <item name="android:layout_height">wrap_content</item> <item name="android:textColor">#FF0000</item> </style> </resources>
As you can see, it's a simple XML containing a style node which has 3 items. Each item represents an attribute and its value. The style node also has a "name" attribute and a "parent" one.
The name is the unique identificator for this style, this is the name that you will later use to refer to this style.
The parent is an optional vattribute that specifies the resource ID of another style from which this style should inherit properties. This way you can override the inherited style properties if needed. The resource can be of any type as long as it contains the needed style. It is recommended that you always inherit the default styles for the specific views - directly or indirectly.
After the style is created, you can use it by simply setting the style property of a View.
<TextView style="@style/SpecialText" android:text="Special text!" />
Note that the style attribute does not need an android: prefix.
If you apply a style to a ViewGroup container, the style will NOT be inherited by its children. To make it inheritable, set the style as a theme.
To set a theme to the whole application (all of its Activities), go to the AndroidManifest XML file and set the android:theme property of the application node:
If you want to set it to a single Activity, just do the same with the activity tag.
There are also a few pre-built themes that you can use. Theme.Dialog, for instance, displays an Activity like a dialog window:
If you want to create a new theme based on an existing one, you can add the base theme as the parent of the style.
That's all for today.
Thanks for reading!