Sunday, February 12, 2012

Styling an Android button the easy way

There are a lot of tutorials on how to this, even the android developers documentation talks about the 9-patch tool.
It can be a bit confusing but I guess if you've got the time you should always read as much as you can on each topic.

The easy steps are:
  1. Just open your favorite png editor (GIMP?) and create the background for your button
    Raw button
    This only takes 30 seconds in your favorite graphics editor.
  2. It is at this point where you need to open the "draw9patch" tool you can find in your "android-sdk/tools" folder.
    Using this tool you open the file you just created.
    draw9patch tool
    You see I've already marked the areas I want the button to repeat. It will tell Android that which parts of the image it should tile/repeat when re/sizing the background to fit buttons of different sizes.
    It also shows you the preview in the right side.
  3. Now to save your image. Point the draw9patch to your "res/drawable" folder and give the image a name. Let's call it "green_button_style.png". After save, you'll notice the tool has actually created a file named "green_button_style.9.png". Don't let the additional "9" fool you. When using the resource identifier, it will be left out.
  4. Now you'll want to point the background of your buttons to this graphic. Open your layout's xml and  find the button you want to style. Add the background attribute (android:background) and use the identifier for your new image which is "drawable/green_button_style" (as I said, you leave the "9" part out).

    Code for the styled android button
That's it, you're done!

1 comment: