i want to change background after clicking Button in android with kotlin
Solution 1
background
requires a Drawable
, but you are passing a color resource.
- You can use
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)
Solution 2
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)
Related videos on Youtube
Nour Medhat
Updated on February 16, 2020Comments
-
Nour Medhat over 4 years
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