我有一个布局:
<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)))