我有一个布局:
<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
具有方法background
,该方法返回RippleDrawable
,我看到了this question,但它不起作用,可能已过期。如何以编程方式获取
MaterialButton
的背景颜色?
最佳答案
在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)))
关于android - 如何在Kotlin Android中的MaterialButton中获取背景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62191132/