如何在kotlin android中的MaterialButton中获取背景颜色 [英] How to get background color in MaterialButton in kotlin android
问题描述
我有一个布局:
<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>
在我的片段中,我可以这样设置背景颜色:
in my fragment I can set background color in this way:
favorite_color1.setBackgroundColor(color)
MaterialButton
有一个方法 background
返回一个 RippleDrawable
,我看到了 这个问题 但它不起作用,而且可能已经过时了.
A MaterialButton
has a method background
that returns a RippleDrawable
and I saw this question but it doesn't work and it is out of date probably.
如何以编程方式获取MaterialButton
的背景颜色?
How Can I get background color for a MaterialButton
programmatically?
推荐答案
在 MaterialButton
中,背景颜色由 app:backgroundTint
定义> 属性(不是 background
属性).
In the MaterialButton
the background color is defined by the app:backgroundTint
attribute (not the background
attribute).
设置/获取背景颜色的相关方法有:
The related method to set/get the background color are:
setBackgroundColor
setBackgroundTintList
getBackgroundTintList
在您的情况下,您可以使用:
In your case you can use:
button.getBackgroundTintList()
这是一个ColorStateList
.
您可以使用以下方法获取每个状态的颜色:colorStateList.getColorForState
.
例如:
textView.setTextColor(
colorStateList!!.getColorForState(
intArrayOf(android.R.attr.state_enabled), 0))
或在 Java 中:
or in java:
textView.setTextColor(colorStateList.getColorForState(
new int[] { android.R.attr.state_enabled},0));
只是一个注释.
如果您使用 setBackgroundColor
方法,例如 favorite_color1.setBackgroundColor(color)
,上面的代码将不起作用.
Just a note.
If you are using the setBackgroundColor
method like favorite_color1.setBackgroundColor(color)
the code above doesn't work.
你必须使用方法 setBackgroundTintList
favorite_color1.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.color)))
这篇关于如何在kotlin android中的MaterialButton中获取背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!