Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

i want to change background after clicking Button in android with kotlin

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

like image 910
Nour Medhat Avatar asked Aug 26 '17 08:08

Nour Medhat


People also ask

How do I change the button background in Kotlin?

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.

How can I change background color of a button?

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.


2 Answers

background requires a Drawable, but you are passing a color resource.

  1. You can use setBackgroundColor to set a color resource:

bm.setBackgroundColor(R.color.green)

  1. setBackgroundResource can be used to set a drawable resource:

bm.setBackgroundResource(R.drawable.green_resource)

  1. background property can be used to set a drawable:

bm.background = ContextCompat.getDrawable(context, R.drawable.green_resource)

like image 128
Bob Avatar answered Nov 04 '22 11:11

Bob


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)
like image 42
Patrick Herbeuval Avatar answered Nov 04 '22 11:11

Patrick Herbeuval