Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android set button background programmatically

Tags:

android

button

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!!

like image 327
pearmak Avatar asked Dec 12 '12 14:12

pearmak


People also ask

How can change button background drawable in android programmatically?

If you want to do this programmatically then you just have to do: button. setBackgroundResource(R. drawable.

How can change background color of button in Android?

To set Android Button background color, we can assign android:backgroundTint XML attribute for Button in layout file with the required Color Value. To programmatically set or change Android Button background color, we may call pass the method Button.

How do I change the default background color in Android Studio?

Create background color. By default each activity in Android has a white background. To change the background color, first add a new color definition to the colors. xml file in the values resource folder like the following.


1 Answers

R.color.red is an ID (which is also an int), but is not a color.

Use one of the following instead:

// If you're in an activity: Button11.setBackgroundColor(getResources().getColor(R.color.red)); // OR, if you're not:  Button11.setBackgroundColor(Button11.getContext().getResources().getColor(R.color.red)); 

Or, alternatively:

Button11.setBackgroundColor(Color.RED); // From android.graphics.Color 

Or, for more pro skills:

Button11.setBackgroundColor(0xFFFF0000); // 0xAARRGGBB 
like image 193
Cat Avatar answered Oct 13 '22 20:10

Cat