【问题标题】:Set Background Color to MaterialCardView in kotlin?在kotlin中将背景颜色设置为MaterialCardView?
【发布时间】:2019-07-19 10:53:09
【问题描述】:

我尝试为我的 MaterialCardView 设置背景颜色,但我没有得到我期望的结果,我尝试了以下方式:

card.setBackground = R.color.red_color

我认为是因为我的 MaterialCardView 显示的 alpha 十六进制数字没有背景:

card.setCardBackgroundColor(0xB00020)

我可以用颜色显示我的卡片的唯一方法是这样,但 MaterialCardView 显示透明,如果我输入例如 0xFFB00020,Android Studio 会抛出错误,因为该函数需要一个整数,但我不能了解,为什么我的 ide 会抛出错误?,如果假设我将十六进制数作为参数传递:

card.setcardBackgroundColor(0x79B00020)

这是我的代码:

 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)
                    }
                }
            }
        }
    }

第一种情况给我带来了 0xFF 的错误...

编辑

我找到了解决方案! 为了在 Kotlin 中为 MaterialCardView 设置背景颜色,必须将十六进制值解析为 Int,例如:0xFFCA4B02.toInt() 但是有人可以解释一下为什么在 kotlin 中这是必要的?

希望有人可以帮助我,问候。

【问题讨论】:

  • 您是否尝试过在 Alpha 十六进制数字中使用 FF?那应该消除透明度????
  • 是的,我尝试使用 0xFFB00020 值,但 Kotlin 中的 Android Studio 会抛出错误
  • 有意思,这个错误到底说了什么?
  • 抛出这个:None of the following functions can be called with the arguments supplied. setCardBackgroundColor(ColorStateList?) defined in com.google.android.material.card.MaterialCardView setCardBackgroundColor(Int) defined in com.google.android.material.card.MaterialCardView

标签: android kotlin material-design


【解决方案1】:

我刚刚测试了为颜色创建资源并将其作为参数传递,但它没有应用任何透明度:

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

【讨论】:

  • 感谢您的帮助!,我没有尝试您的方式,我会尝试。谢谢!
【解决方案2】:

尝试这样的事情,因为它需要解析颜色。 我添加的颜色是RED

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

【讨论】:

  • 谢谢,为我工作node.setCardBackgroundColor(0xFF7903DAC6.toInt())
  • 没问题,即使您发现了问题,也很乐意为您提供帮助。
猜你喜欢
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 2021-03-23
  • 2010-11-08
  • 2020-12-06
  • 1970-01-01
  • 1970-01-01
  • 2011-06-06
相关资源
最近更新 更多