Pages

Sunday, 22 May 2011

Defining a custom button with background and textcolor styles

How do I define a custom button with background and text color styles?

This is a simple guide to styling buttons within your Android app. We start of with a button in your Layout, and set the style to a custom style name:

<Button
  android:id="@+id/myButton"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Tap me!"
  style="@style/button" />

It is a good idea to use a style rather than set the background directly as it allows you to set the text properties as well as background graphic options. It also makes it very easy to re-use your style.

res/values/styles.xml
<style name="button">
  <item name="android:background">@drawable/button</item>
  <item name="android:textColor">#FFF</item>
  <item name="android:textSize">16sp</item>
  <item name="android:gravity">center_vertical|center_horizontal</item>
</style>

The background of a Button is expected to be a Drawable (image), but we are able to define this as a shape with an item for each state (pressed, focussed or default). To keep this simple we'll stick to simple colour changes:

res/drawable/button.xml
<?xml version="1.0" encoding="utf-8"?>    
<selector xmlns:android="http://schemas.android.com/apk/res/android">

  <item android:state_pressed="true" >
    <shape>
      <solid android:color="#FF0000" />
    </shape>
  </item>

  <item android:state_focused="true" >
    <shape>
      <solid android:color="#DDDDDD" />
    </shape>
  </item>

  <item>
    <shape>
      <solid android:color="#FFFFFF" />
    </shape>
  </item>

</selector>

You may want to produce more fancy buttons, in which case you will need to use more shape options (such as rounding and strokes) or produce a Drawable image for each state. If you want to use images, these should be 9-Patch PNGs that allow Android to stretch the image to fit any content. I will cover these another day!

0 comments:

Post a Comment