Reputation: 3
I had been searching how to change color for the background of a button and I the closest I got for that was using
view.setBackgroundColor(ContextCompat.getColor(this, R.color.white))
But when I do that the button doesn't turn white, it turns purple? That's like the default color for buttons, and I really don't know what to do.
Thank you for your help and I'm sorry if I don't reply :( I can't understand how to use this page very well
Upvotes: 0
Views: 623
Reputation: 363677
Use the setBackgroundTintList
instead of the setBackgroundColor
.
Something like:
button.backgroundTintList = ContextCompat.getColorStateList(this,R.color.xxxx);
You can use a simple color:
<color name="red600">#e53935</color>
or better a selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="?attr/colorPrimary" android:state_enabled="true"/>
<item android:alpha="0.12" android:color="?attr/colorOnSurface"/>
</selector>
The default background color is defined by the colorPrimary
attribute in your theme.
Upvotes: 1
Reputation: 556
You can easily change the color on runtime with the help of these
// In Java btn.setBackgroundColor(btn.getContext().getResources().getColor(R.color.red));
In kotlin
btn.setBackgroundColor(this.getResources().getColor(R.color.red));
or
btn.setBackgroundColor(Color.RED);
and with the help of RGB : 0xAARRGGBB
btn.setBackgroundColor(0xFFFF0000);
Upvotes: 0