首页 > 解决方案 > 如何在 Android Studio 项目的应用程序主题中嵌套按钮样式元素

问题描述

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

我的主题/样式 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" />

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

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

标签: javaandroidmaterial-designthemes

解决方案


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

首先,为您的按钮创建一个主题,并使其继承 AppCompat 按钮(虽然它是一个材质按钮)。例如:

<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>

这应该可以解决问题:)


推荐阅读