I want to change background after clicking Button
var bm : Button = messeg
bm . setOnClickListener {
bm . background = R.color.green
}
Error Log:
Error:(35, 31) Type mismatch: inferred type is Int but Drawable! was expected Error:Execution failed for task ':app:compileDebugKotlin'.
Compilation error. See log for more details
To programmatically set or change Android Button background color, we may call pass the method Button. setBackgroundColor() on the button reference and pass Color object as argument.
To change the background color of the button, use the CSS background-color property and give it a value of a color of your taste. In the . button selector, you use background-color:#0a0a23; to change the background color of the button.
background
requires a Drawable
, but you are passing a color resource.
setBackgroundColor
to set a color resource:bm.setBackgroundColor(R.color.green)
setBackgroundResource
can be used to set a drawable resource:bm.setBackgroundResource(R.drawable.green_resource)
background
property can be used to set a drawable:bm.background = ContextCompat.getDrawable(context, R.drawable.green_resource)
The current accepted answer is wrong for setBackgroundColor(). In the given example, you set the color to the resource id, but you must pass the color directly.
This won't fail because both values are int, but you'll get weird colors.
Instead of that, you should retrieve first the color from the resource, then set it as background. Example :
val colorValue = ContextCompat.getColor(context, R.color.green)
bm.setBackgroundColor(colorValue)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With