如何在 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)

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

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

MaterialButton中,背景颜色由app:backgroundTint属性(而不是background属性(定义。

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

  • setBackgroundColor
  • setBackgroundTintList
  • getBackgroundTintList

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

button.getBackgroundTintList()

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

例如:

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

或在爪哇中:

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

只是一个笔记。
如果您使用的是像favorite_color1.setBackgroundColor(color)这样的setBackgroundColor方法,则上面的代码不起作用。

您必须使用该方法setBackgroundTintList

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

最新更新