Search code examples
androidkotlinandroid-buttonmaterial-componentsmaterialbutton

How to get background color in MaterialButton in kotlin android


I have a layout:

<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)

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.

How Can I get background color for a MaterialButton programmatically?


Solution

  • 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()
    

    This is a ColorStateList.
    You can get the color of each state with the method: colorStateList.getColorForState.

    For example:

    textView.setTextColor(
            colorStateList!!.getColorForState(
          intArrayOf(android.R.attr.state_enabled), 0))
    

    or in java:

    textView.setTextColor(colorStateList.getColorForState(
         new int[] { android.R.attr.state_enabled},0));
    

    Just a note.
    If you are using the setBackgroundColor method like favorite_color1.setBackgroundColor(color) the code above doesn't work.

    You have to use the method setBackgroundTintList

    favorite_color1.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.color)))