android - 如何在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
解决方案
在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)))
推荐阅读
- reactjs - 无法使用异步映射读取 null 类型的属性
- java - spring boot 应用程序没有在 Jenkins 中启动
- tsql - t-sql where = null 含义
- c - 为 Linux 创建 C 程序时出现浮点异常(核心转储)
- javascript - 我正在使用反应导航 v5。我在抽屉导航中有堆栈导航。每次单击抽屉项目时如何获得初始屏幕?
- google-apps-script - 用于从 Google 表格内部生成自定义电子邮件的 Google-Sheets 应用脚本
- r - R:如何有效地可视化大型图网络
- reactjs - 将 react.js 与 C# 项目集成
- string - Haskell 将字符串列表转换为字符串
- spring - 如何对 datagrid primefaces 中的数据进行排序?