【问题标题】:How to change drawable background color from code (Java/Kotlin) file如何从代码(Java/Kotlin)文件更改可绘制背景颜色
【发布时间】:2020-07-06 09:56:43
【问题描述】:

我创建了以下可绘制对象并将其设置为代码中的按钮背景。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="8dp"/>
    <solid android:color="@color/background_profile"/>
    <padding android:left="8dp" android:top="7dp" android:right="8dp" android:bottom="6dp" />
</shape>

Kotlin 文件

  btn?.background= resources?.getDrawable(R.drawable.drawable_rewards)

现在我将从我的服务中获取颜色,例如 "#00000",我需要更新 drawable_rewards.xml 文件中的颜色。

有什么方法可以动态改变drawable文件的颜色。

【问题讨论】:

  • 您可以使用MaterialButton(默认为圆角)并使用backgroundTint 更改背景颜色。

标签: android android-layout kotlin android-drawable


【解决方案1】:
    val wrappedDrawable: Drawable = DrawableCompat.wrap(ContextCompat.getDrawable(context!!, R.drawable.drawable_rewards)!!)
    DrawableCompat.setTint(wrappedDrawable, ContextCompat.getColor(context!!, R.color.colorPrimary))
    btn?.background = wrappedDrawable

【讨论】:

    【解决方案2】:

    答案是您将按钮的背景设置为可绘制 -> 更改可绘制的颜色 -> 将可绘制设置为按钮的背景

                val drawable: Drawable = buttonChange.background
                drawable.setColorFilter(Color.GREEN, PorterDuff.Mode.SRC)
                buttonChange.background = drawable
    

    【讨论】:

      【解决方案3】:
      fun View.setBgColor(color: String?) {
          val bgColor = parseColor(color) ?: return
          val drawable = if (background is InsetDrawable)
              (background as InsetDrawable).drawable
          else
              background
      
          when (drawable?.mutate()) { //mutate before change is important
              is ShapeDrawable -> (drawable as ShapeDrawable).paint.color = bgColor
              is GradientDrawable -> (drawable as GradientDrawable).setColor(bgColor)
              is ColorDrawable -> (drawable as ColorDrawable).color = bgColor
          }
      }
      
      fun parseColor(color: String?): Int? {
          return try {
              Color.parseColor(color)
          } catch (e: Exception) {
              null
          }
      }
      

      【讨论】: