Android: MaterialButton 覆盖 Style 中的 textColor

Android: MaterialButton override textColor in Style

我想定义一个替代按钮样式,它使用我的 secondaryColor 作为背景,?colorOnSecondary 分别用于文本。

但我正在努力获取样式中定义的 textColor。 MaterialButton 正在为使用 ?colorOnPrimary 的 textColor 使用(私有)选择器可绘制对象。 所以覆盖起来很麻烦。

没有selectorDrawable还有其他设置颜色的方法吗?

如果只想覆盖按钮的颜色,可以使用materialThemeOverlay属性(需要1.1.0版本)。
类似于:

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

否则你可以自定义样式:

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

其中 my_bg_color_selector.xml 可以是这样的:

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

my_text_color_selector.xml可以是:

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