Camper1233 Camper1233 - 4 months ago 10
Android Question

Android studio setting a hex color value for a button with code

I would like to change the button color on click, I have used the following code

button.setBackgroundColor(#ff512e);
but it did not work. I have googled it and I couldn't find an answer. I'm aware that I could just change it in the XML code but I need it to be changed once the button is clicked. I have set listeners and everything else that is needed I just need the code to set the button color with a hex value on click.

Answer

setBackgroundColor(int) method takes integer as an argument but you are passing a String in the code.

Use this instead to parse the hex code of color to int:

button.setBackgroundColor(Color.parseColor("#ff512e"));