为什么顶部栏的背景颜色会自动变化而不是按照我设置的变化?材料设计3

Tah*_*ami 1 android material-design android-toolbar material-components-android

我正在尝试更改顶部栏的背景颜色并使其像主背景一样。我正在使用Material You (MD3)。

用户可以从浅色模式更改为深色模式,反之亦然。

这是我尝试做的:

值\主题.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Theme.App" parent="Theme.Material3.Light.NoActionBar">
        <item name="android:colorBackground">@color/md_theme_light_background</item>
        ...
    </style>
</resources>
Run Code Online (Sandbox Code Playgroud)

值夜\themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Theme.App" parent="Theme.Material3.Dark.NoActionBar">
        <item name="android:colorBackground">@color/md_theme_dark_background</item>
        ...
    </style>
</resources>
Run Code Online (Sandbox Code Playgroud)

颜色.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="md_theme_light_background">#FCFDF7</color>
    <color name="md_theme_dark_background">#1A1C19</color>
    ...
</resources>
Run Code Online (Sandbox Code Playgroud)

活动主文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".activities.MainActivity">

    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/topBar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?android:attr/colorBackground"
        android:elevation="4dp"
        app:title="@string/app_name" />

    ...

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

结果(深色模式)

在此输入图像描述

正如你所看到的,顶部栏的背景颜色一定是,#1A1C19但它变成了#222E22,从哪里来的#222E22?

我试图在 MD3 文档中找到任何有关此内容的内容,但没有找到任何内容。你能告诉我为什么颜色会自动改变吗?

注意:如果我md_theme_dark_background从#1A1C19改为#1A1C18,顶栏的背景颜色将与主背景相同,不会改变。但是当返回它时#1A1C19它会将其转换为#222E22.

这是正常行为还是错误?

谢谢。

DrH*_*Doo 5

不同的颜色是由于高程叠加造成的。您可以删除标高或禁用标高叠加。

要禁用主题中的海拔覆盖,请在主题中添加以下行:

<item name="elevationOverlayEnabled">false</item>
Run Code Online (Sandbox Code Playgroud)

仅对materialToolBar禁用它:

<style name="Card" parent="Widget.Material3.Toolbar.Surface">
     <item name="materialThemeOverlay">@style/ThemeOverlay.Card</item>
 </style>

<style name="ThemeOverlay.Card" parent="ThemeOverlay.Material3.Toolbar.Surface">
    <item name="elevationOverlayEnabled">false</item>
</style>
Run Code Online (Sandbox Code Playgroud)

然后在您的materialToolBar xml代码中添加这一行:

style="@style/Card"
Run Code Online (Sandbox Code Playgroud)