2

I am trying to apply background color to button dynamically using color id in color resource file(color.xml).

btn.setBackgroundColor(R.color.green);

i also tried this

btn.setBackgroundColor(Resources.getSystem().getColor(R.color.green));

but its not working.

if i apply

btn.setBackgroundColor(Color.Green);

Its working.

But i need to apply color resource from color.xml file. Please let me know how i can do it.

Wesley Wiser
  • 9,491
  • 4
  • 50
  • 69
praveenb
  • 10,549
  • 14
  • 61
  • 83

2 Answers2

7

You should use this:

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

and second way:

Resources resources = YourActivity.this.getResources();  
Drawable drawable = resources.getDrawable(R.color.Green);
btn.setBackgroundDrawable(drawable);

your color.xml look like:

 <?xml version="1.0" encoding="utf-8"?>  
    <resources>  
        <drawable name="red">#f00</drawable>  
        <drawable name="green">#0f0</drawable>  
        <drawable name="gray">#ccc</drawable>  
    </resources>  

**EDIT Now that getColor() is deprecated :

ContextCompat.getColor(context, R.color.color_name)
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
0

Under values create xml called colors, add your custom colors to that one. Now you can write R.color."name" (aka. rename color to colors)

Anders Metnik
  • 6,096
  • 7
  • 40
  • 79