Wednesday, 25 May 2011

First Steps - An introduction to Styles

How do I use styles in my app?
Use of styles allows you to define reusable visual settings to help maintain a consistent look-and-feel to your app.
The simple example below shows how to create a style for titles, which will be larger text, and warnings which will be red. Each style must have a name and can then list multiple properties:

<?xml version="1.0" encoding="utf-8"?>
    <style name="myTitle">
      <item name="android:textSize">16sp</item>
    <style name="myWarning" parent="@style/myTitle">
      <item name="android:textStyle">bold</item>
      <item name="android:textColor">@colors/myRed</item>

A few things to note here, firstly that you can put any styling name into the item tag that you would use within your layout definitions. Also note that myWarnings has its parent set as myTitle and so inherits the 16sp text size defined there. Finally, the textColor value could be a standard hex colour (i.e. #FF0000) but it is good practice to put colours into a separate resource so that one you only need to update one location if you want to change it:

<?xml version="1.0" encoding="utf-8"?>
    <color name="myRed">#FF0000</color>

Now it is simply the case of applying the style within your layouts:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
        android:layout_height="wrap_content" >

        android:text="My styled text view"
        style="@styles/myWarning" />

Note that the style attribute is not prefixed by the android tag.


Post a Comment