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

28,704

Solution 1

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)

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)
Share:
28,704

Related videos on Youtube

Nour Medhat
Author by

Nour Medhat

Updated on February 16, 2020

Comments

  • Nour Medhat
    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

Related