How to set up button custom colors for enabled, disabled, light and dark

1 day ago 5
ARTICLE AD BOX

I'm struggling to define custom button colors that handle all the different states required: enabled/disabled, light and dark theming, text and background colors.

For the colors in enabled and disabled states for both text and background, I have defined two files:

drawable/btn_text.xml: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_enabled="true" android:drawable="@color/buttonText"/> <item android:state_enabled="false" android:drawable="@color/buttonTextDisabled"/> </selector> drawable/btn_bg.xml: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_enabled="true" android:drawable="@color/buttonBackground"/> <item android:state_enabled="false" android:drawable="@color/buttonBackgroundDisabled"/> </selector>

To support light and dark themes:

values/colors.xml: <?xml version="1.0" encoding="utf-8"?> <resources> ... <color name="buttonBackground">#A9C9FC</color><!-- light blue --> <color name="buttonText">#2C3E50</color><!-- dark blue --> <color name="buttonBackgroundDisabled">#C5C4C4</color><!-- light gray --> <color name="buttonTextDisabled">#525151</color><!-- dark gray --> ... </resources> values-night/colors.xml: <resources> ... <color name="buttonBackground">#2C3E50</color><!-- dark blue --> <color name="buttonText">#A9C9FC</color><!-- light blue --> <color name="buttonBackgroundDisabled">#525151</color><!-- dark gray --> <color name="buttonTextDisabled">#C5C4C4</color><!-- light gray --> ... </resources> style.xml: <style name="myButton" parent="Widget.Material3.Button.OutlinedButton"> <item name="android:textSize">18sp</item> <item name="android:fontFamily">sans-serif</item> <item name="android:textStyle">bold</item> <item name="android:textColor">@drawable/btn_text</item> <item name="android:backgroundTint">@drawable/btn_bg</item> </style>

In the layout button definition:

<com.google.android.material.button.MaterialButton style="@style/myButton" ...

I'm not seeing the colors that I expect. The button is always solid ?fuchsia. What am I doing wrong?

Read Entire Article