首页 > 解决方案 > Button 的背景是 colorPrimary 着色的,而不是 colorAccent 着色的吗?

问题描述

我的设置:minSdkVersion 19 && compileSdkVersion 30

我试过下面的代码。我希望按钮的背景颜色为colorAccent,但它的颜色为colorPrimary。当我将colorPrimary值更改为另一种颜色时,按钮的背景颜色会相应更改。

这与我学到的相反。colorAccent(当样式为“@style/Widget.AppCompat.Button.Colored”时,按钮的背景应着色)。我在学习 Google Android 基础教程( https://developer.android.com/codelabs/kotlin-android-training-interactivity/index.html#4)时遇到了这个问题。

我很困惑,请帮助。

// activity_main.xml
<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:id="@+id/done_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/done" />

// themes.xml
<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.AboutMe" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_500</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>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>

// colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
    <color name="colorAccent">#880000</color>
</resources>

标签: androidandroid-buttonandroid-themeandroid-stylesmaterial-components-android

解决方案


由于您使用的是 Material Components 主题,因此您Button在运行时被替换为MaterialButton.

MaterialButton用作背景色的?attr/colorPrimary. 该样式应用了一个背景可绘制对象,该可Widget.AppCompat.Button.Colored绘制对象被.MaterialShapeDrawableMaterialButton

Button在asWidget.MaterialComponents.Button和 the中使用 Material Components 样式在app:backgroundTint背景中应用不同的颜色:

   <Button
    style="@style/Widget.MaterialComponents.Button"
    app:backgroundTint="@color/....."
    ../>

或者:

  <Button
    style="@style/Widget.MaterialComponents.Button"
    android:theme="@style/ButtonThemeOverlayPrimaryColor"
    ../>


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

或者,如果您想使用AppCompat样式,请使用AppCompatButton.

<androidx.appcompat.widget.AppCompatButton
    style="@style/Widget.AppCompat.Button.Colored"/>

推荐阅读