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