android 中的正确样式 MaterialButton

Proper styling MaterialButton in android

我一直在与 changing/overwriting 默认样式作斗争。 我正在为我的小部件使用新的 material 设计库。 例如,我正在覆盖我的 MaterialButton 样式:

 <style name="AppTheme" parent="Theme.MaterialComponents.NoActionBar">
    ...
    <item name="materialButtonStyle">@style/CustomButton</item>
</style>
...
...
<style name="CustomButton" parent="Widget.MaterialComponents.Button">
    <item name="android:textColor">@color/colorTextPrimary</item>
    <item name="android:backgroundTint">@color/button_background</item>
</style>

背景颜色为:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_enabled="true" android:color="@color/colorAccent"/>
   <item android:state_enabled="false" android:color="@color/colorDisabled"/>
</selector>

问题是这样我无法为禁用颜色设置 alpha,因为它只影响背景颜色而不影响文本颜色... 这种方法的另一个问题是 MaterialDesign.Text 按钮 (Widget.MaterialComponents.Button.TextButton) 也会被覆盖并中断...

我在其他小部件(例如 TextView、InputFields... 在不破坏任何东西的情况下覆盖不同样式的正确方法是什么?我一直在考虑扩展这些 类(如 MaterialButton)并以编程方式进行更改,但它只是感觉我错了,不是常规方式...我错了吗?

您可以使用类似的东西:

<style name="CustomButton" parent="Widget.MaterialComponents.Button">
    <item name="android:textColor">@color/color_selector</item>
    <item name="backgroundTint">@color/button_background</item>
</style>

其中 color_selector 是:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:color="?attr/colorOnPrimary" android:state_enabled="true"/>
  <item android:alpha="0.38" android:color="?attr/colorOnSurface"/>
</selector>

button_background:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:color="?attr/colorPrimary" android:state_enabled="true"/>
  <item android:alpha="0.12" android:color="?attr/colorOnSurface"/>
</selector>