android - 如何在Kotlin Android中的MaterialButton中获取背景色

标签 android kotlin android-button material-components 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具有方法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/

    相关文章:

    android - 为什么我的 "centered"对象在我的 RelativeLayout 中稍微偏离中心?

    android - Google Play 商店应用提交规则

    android - 如何设置使用 Kotlin 检查的 RecyclerView 中的第一个单选按钮?

    android - 在按钮android中设置图像

    android - 如何在按钮的点击状态下设置背景、文字颜色和角?

    android - 如何在 Android 中单击按钮调用两个函数?

    android - Qt 5 在Android 上解析HTML

    android - TextView 由于某种原因无法清除,Android

    android - 在 Android 中以编程方式添加 FilterChips

    android - RxJava 和改造的单元测试