0

I created an Android app with a 4x6 grid of buttons. This buttons should all have different background colors.

I could achieve this by creating 24 custom shapes like drawable\red_botton.xml, drawable\green_botton.xml, ... and set them as android:background property.

But this would produce tons of redundant xml code. Is there a better way?

Euro
  • 618
  • 2
  • 8
  • 12
  • 1
    Define it without color and set the color programatically: http://stackoverflow.com/questions/2173936/how-to-set-background-color-of-a-view - via `.setColorFilter` http://stackoverflow.com/questions/11036835/how-to-apply-a-color-filter-to-a-view-with-all-children – zapl Aug 21 '13 at 17:44
  • Finally I decided to set the background property directly to a color and just use the resulting simple colored squares as buttons. Thanks anyway for the hint to `setColorFilter`! – Euro Aug 21 '13 at 20:54

1 Answers1

1

Create colors.xml file at res/values folder:

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <color name="black">#000</color>
 <color name="blue">#00f</color>
 <color name="red">#f00</color>
</resources>

then use following code on button object

btn.setBackgroundColor(getResources().getColor(R.color.red));

or you can set in you layout file.

CodingRat
  • 1,934
  • 3
  • 23
  • 43