cwiesner
cwiesner

Reputation: 952

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?

Upvotes: 7

Views: 7751

Answers (1)

Gabriele Mariotti
Gabriele Mariotti

Reputation: 364371

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>

Upvotes: 16

Related Questions