如何在 Android Studio 项目的应用程序主题中嵌套按钮样式元素

How to nest button style element within app theme in Android Studio project

我正在尝试将 Material 按钮背景颜色定义为我的 Android 应用程序中的主题,以便所有按钮都从应用程序主题中获取样式。我的 Android 应用程序中定义了以下样式。

我的 theme/style xml 文件中有以下内容

<style name="Theme.SimpleTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    <!-- Some theming -->
</style>

<style name="SimpleButton" parent="Widget.MaterialComponents.Button">
    <item name="colorPrimary">@color/blue_grey_800</item>
    <item name="colorOnPrimary">@color/white</item>
</style>

然后在布局文件中,我有:

<com.google.android.material.button.MaterialButton
    android:theme="@style/SimpleButton" />

现在,这可以让特定按钮具有我想要的背景颜色,但我必须在所有布局文件中的所有 material 按钮元素中设置 Style 属性。

有什么方法可以嵌套样式,这样我就不需要在所有按钮中明确提及样式了吗?

是的,有办法做到这一点。

首先,为您的按钮创建一个主题,并使其继承 AppCompat Button(尽管它是一个 material 按钮)。 例如:

<style name="bTheme" parent="Widget.AppCompat.Button">
        <item name="android:backgroundTint">@color/black</item>
        <item name="android:textColor">@color/white</item>
</style>

然后,在主应用的主题上,添加以下行:

<item name="materialButtonStyle"> @style/bTheme</item>

这应该可以解决问题:)