leoLR
leoLR

Reputation: 487

Set Background Color to MaterialCardView in kotlin?

I try to set background color to my MaterialCardView, but I dont have the result that I expected, I tryied with the following ways:

card.setBackground = R.color.red_color

I thought because the alpha hex numbers my MaterialCardView shows without background:

card.setCardBackgroundColor(0xB00020)

The only way that I can display my cards with color is with this, but the MaterialCardView shows with transparency, if I put for example 0xFFB00020, Android Studio throws me error, because the function expects an Integer, but I can't understand, why my ide throws me error?, if is supposed that I pass hexadecimal number as param:

card.setcardBackgroundColor(0x79B00020)

This is my code:

 override fun onBindViewHolder(holder: TableHolder, position: Int) {
        if (position < tableList.size) {
            val table = tableList[position]
            val node = holder.table
            //Log.e("NODE", node.toString())
            holder.guestNumber.text = table.people.toString()
            holder.tableName.text = table.description
            if (node is MaterialCardView) {
                when (table.status) {
                    "A" -> {
                        holder.descriptionTable.text = "ABIERTA"
                        node.setCardBackgroundColor(0xFF7903DAC6)
                    }
                    "D" -> {
                        holder.descriptionTable.text = "DISPONIBLE"
                        node.setCardBackgroundColor(0x79CA4B02)
                    }
                    "C" -> {
                        holder.descriptionTable.text = "CERRADA"
                        node.setCardBackgroundColor(0x79FF0266)
                    }
                    else -> {
                        holder.descriptionTable.text = node.context.getString(R.string.error_label)
                        node.setCardBackgroundColor(0x79B00020)
                    }
                }
            }
        }
    }

The first case throws me error for the 0xFF...

EDIT

I Found the solution! For set background color to MaterialCardView in Kotlin is necessary parse the hexadecimal value to Int, for example: 0xFFCA4B02.toInt() But someone can explain me why this is necessary in kotlin?

I hope someone can help me, regards.

Upvotes: 0

Views: 3585

Answers (2)

amilcar-sr
amilcar-sr

Reputation: 1060

I just tested creating a resource for the color and passing it as param like this, and it didn't apply any transparency:

val cardColor = ContextCompat.getColor(context!!, R.color.card_background)
node.setCardBackgroundColor(cardColor)

Upvotes: 2

TheCoderGuy
TheCoderGuy

Reputation: 883

Try something like this because it need to parse the color. The color which I added it is RED

node.setCardBackgroundColor(Color.parseColor("#ffff0000"));

Upvotes: 0

Related Questions