Android

Apply Button background color dynamically Android

Different ways of applying Button background color

To apply basic Colors as Button background, you can use default Color class

btn.setBackgroundColor(R.color.green);
(here btn is instance of a Button view).

To apply Colors using color resources in color.xml file

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

your color.xml look like

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="green">#088e0b</color>
</resources>

and To apply background as color drawable, using color resources in color.xml file

Drawable drawable = resources.getDrawable(R.color.green);
btn.setBackgroundDrawable(drawable);
btn.setBackground(drawable);

your color.xml look like

<?xml version="1.0" encoding="utf-8"?>
<resources>
<drawable name="green">#088e0b</color>
</resources>

Hope it helps somebody

Cheers 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *