首页 > 解决方案 > 如何在kotlin android的MaterialButton中获取背景颜色

问题描述

我有一个布局:

<com.google.android.material.button.MaterialButtonToggleGroup
    ...
    app:checkedButton="@+id/favorite_color1"
    app:singleSelection="true">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/favorite_color1"
        ... />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/favorite_color2"
        ... />

</com.google.android.material.button.MaterialButtonToggleGroup>

在我的片段中,我可以通过这种方式设置背景颜色:

favorite_color1.setBackgroundColor(color)

AMaterialButton有一个background返回 a 的方法,RippleDrawable我看到了这个问题,但它不起作用,而且它可能已经过时了。

如何以编程方式获取背景颜色?MaterialButton

标签: androidkotlinandroid-buttonmaterial-componentsmaterialbutton

解决方案


MaterialButton背景色中是由app:backgroundTint属性(不是background属性)定义的。

设置/获取背景颜色的相关方法是:

  • setBackgroundColor
  • setBackgroundTintList
  • getBackgroundTintList

在您的情况下,您可以使用:

button.getBackgroundTintList()

这是一个ColorStateList.
您可以使用以下方法获取每个状态的颜色:colorStateList.getColorForState

例如:

textView.setTextColor(
        colorStateList!!.getColorForState(
      intArrayOf(android.R.attr.state_enabled), 0))

或在java中:

textView.setTextColor(colorStateList.getColorForState(
     new int[] { android.R.attr.state_enabled},0));

只是一个注释。
如果你使用上面代码setBackgroundColor这样的方法是favorite_color1.setBackgroundColor(color)行不通的。

你必须使用方法setBackgroundTintList

favorite_color1.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.color)))

推荐阅读