MeowYOU
MeowYOU

Reputation: 3

How can I set BackgroundColor on Kotlin for button?

Here's a imagen of my situation

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

Answers (2)

Gabriele Mariotti
Gabriele Mariotti

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

Muhammad Ammar
Muhammad Ammar

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

Related Questions