首页 > 解决方案 > Android材质按钮采用颜色原色而不是颜色重音

问题描述

我的布局按钮为 -

<com.google.android.material.button.MaterialButton
  android:id="@+id/save_button"
  style="@style/buttonView"
  android:text="Save"
  app:layout_constraintBottom_toBottomOf="parent"
  app:layout_constraintStart_toStartOf="parent" />

在我的styles.xml,我有 -

<style name="buttonView" parent="Theme.MyTheme">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_marginStart">16dp</item>
        <item name="android:layout_marginLeft">16dp</item>
        <item name="android:layout_marginTop">16dp</item>
        <item name="android:layout_marginEnd">16dp</item>
        <item name="android:layout_marginRight">16dp</item>
    </style>

在我的themes.xml,我有 -

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.MyTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_500</item>
        <item name="android:textColorPrimary">@color/black</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!--- Accent color. -->
        <item name="colorAccent">@color/red</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant
        </item>
        <!-- Customize your theme here. -->
    </style>
</resources>

根据 Android 文档,所有 UI 元素(例如 FAB、textview、编辑文本、按钮)都采用颜色强调。所以我希望我的按钮colorAccent默认采用,但为什么要采用colorPrimary. 我做错什么了吗?

标签: androidkotlinandroid-buttonandroid-stylesmaterial-components-android

解决方案


你可以查看官方文档

填充按钮具有backgroundTint基于colorPrimary.
同样在您的buttonView样式中,您应该扩展提供的样式之一:

Default style           Widget.MaterialComponents.Button
Icon style              Widget.MaterialComponents.Button.Icon
Unelevated style.       Widget.MaterialComponents.Button.UnelevatedButton
Unelevated icon style   Widget.MaterialComponents.Button.UnelevatedButton.Icon

例子:

<style name="buttonView" parent="Widget.MaterialComponents.Button">

</style>

如果要更改背景颜色,可以:

  • backgroundTint在您的自定义样式中使用该属性

  • 使用(最佳解决方案)覆盖colorPrimary自定义样式中的属性materialThemeOverlay

例子:

<style name="buttonView"parent="Widget.MaterialComponents.Button">
   <item name="materialThemeOverlay">@style/CustomButtonThemeOverlay</item>
</style>

<style name="CustomButtonThemeOverlay">
  <item name="colorPrimary">@color/...</item>
</style>

推荐阅读