Android:MaterialButton 覆盖样式中的 textColor

cwi*_*ner 6 android android-button material-components material-components-android

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

但是我很难在样式中定义 textColor 。MaterialButton 正在为使用?colorOnPrimary. 因此,重写很麻烦。

有没有另一种方法可以在没有 selectorDrawable 的情况下设置颜色?

Gab*_*tti 14

如果只想覆盖按钮的颜色,可以使用该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>
Run Code Online (Sandbox Code Playgroud)

否则,您可以定义自定义样式

<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> 
Run Code Online (Sandbox Code Playgroud)

哪里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>
Run Code Online (Sandbox Code Playgroud)

并且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>
Run Code Online (Sandbox Code Playgroud)