Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: MaterialButton override textColor in Style

I want to define an alternative Button Style that uses my secondaryColor as background and the ?colorOnSecondary respectively for the text.

But I'm struggling to get the textColor defined in a style. The MaterialButton is using a (private) selector-drawable for the textColor which uses ?colorOnPrimary. So this is cumbersome to override.

Is there another way to set the color without the selectorDrawable?

like image 777
cwiesner Avatar asked Oct 09 '19 12:10

cwiesner


1 Answers

If you want to override the colors only for the buttons, you can use the materialThemeOverlay attribute(it requires the version 1.1.0).
Something like:

  <style name="MyButtonTheme" parent="Widget.MaterialComponents.Button">
    <item name="materialThemeOverlay">@style/ButtonStyleTextColor</item>
  </style>

  <style name="ButtonStyleTextColor">
    <item name="colorOnPrimary">@color/...</item>
    <item name="colorOnSecondary">@color/...</item>
    <item name="colorOnSurface">....</item>
    .....
  </style>

Otherwise you can define a custom style:

<style name="CustomButtonStyle" parent="Widget.MaterialComponents.Button">
  <item name="backgroundTint">@color/my_bg_color_selector</item>
  <item name="android:textColor">@color/my_text_color_selector</item>
</style> 

Where my_bg_color_selector.xml can be something like:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:color="@color/..." android:state_enabled="true"/>
  <item android:alpha="0.12" android:color="@color/..."/>
</selector>

and my_text_color_selector.xml can be:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:color="@color/..." android:state_enabled="true"/>
  <item android:alpha="0.38" android:color="@color/..."/>
</selector>
like image 118
Gabriele Mariotti Avatar answered Nov 15 '22 09:11

Gabriele Mariotti