Custom color buttons for Android (9-patch images + example project)
Posted / Публикувана 2011-02-15 in category / в категория: Android
On several occasions I had to create simple buttons that use different background color than the default gray. I've tried to google for already cooked solution but quite surprisingly -- I was unable to find one that suits me so I had to create solution by my self (not really, I just combined other solutions in one easy to use packaged solution).
There are three approaches:
1. First approach (bad) -- just set the background to some color like this
a) button does not have rounded edges (and does not fit in the look & feel, i.e. looks alien)
b) does not support changes of the color to indicate focus or pressed state.
2. Second approach (not very good) -- create custom drawable definitions in xml file that use gradients (<gradient>). The problem is that buttons don't look quite the same as default buttons -- edges are not quite with the same roundness, margins and paddings are different. When I first tried to create colored buttons I've tried this approach but after 2-3 hours playing with paddings and roundess I finally gived up.
3. Third approach (the right(eous) one) -- Use different 9-patch images for the different colors.
It works very simple:
3.1. Create images 9-patch images for the different colors that you need and put them into drawable-hdpi and drawable-mdpi (yes, you will need two versions if you want your buttons to look good on different devices).
3.2. Create XML files with <selector> for each color (in the example project drawable/custom_button_*.xml)
3.3. Use your new buttons in your layout (in the example project main.xml)
Warning: because default android drawables for buttons are inaccessible (i.e. private and cannot be referenced from layout XML) I had to copy default images in drawable-hdpi and drawable-mdpi. In the future (next version of Android) Google may decide to change default images and this may lead to inconsistent look of the applications that use custom buttons. The solution is to stick your apps to all custom buttons or all default buttons.
Running the project should result in something like: