I would like to know how to set the button color programatically? I have coded the following but fails:
Button11.setBackgroundColor(R.color.red);
Thanks!!
I would like to know how to set the button color programatically? I have coded the following but fails:
Button11.setBackgroundColor(R.color.red);
Thanks!!
Old thread, but learned something new, hope this might help someone.
If you want to change the background color but retain other styles, then below might help.
You can set your desired color to the button programmatically like:
Also you can give the text color for a button like:
R.color.red
is an ID (which is also anint
), but is not a color.Use one of the following instead:
Or, alternatively:
Or, for more pro skills:
Sets the background color for this view. Parameters: color the color of the background
R.color.red
is a reference generated at the compilation in gen.I have found that Android Studio gives me a warning that
getColor()
is deprecated when trying to do this:So I found doing the method below to be the simple, up-to-date solution:
You want to avoid hard-coding in the color argument, as it is considered bad code style.
Edit: After using
setBackgroundColor()
with my own button, I saw that the internal button padding expanded. I couldn't find any way of changing it back to having both height and width set to "wrap_content". Maybe its a bug.Source: https://stackoverflow.com/a/32202256/6030520
For not changing the size of button on setting the background color:
this didn't change the size of the button and works with the old android versions too.