Android: MaterialButton override textColor in Style

放肆的年华 提交于 2019-12-11 06:55:42

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/58303790/android-materialbutton-override-textcolor-in-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!