首页 > 解决方案 > Android 主题/颜色:设置原色时,强调色完全不可见

问题描述

我的应用程序的一些概述:我正在使用 Google Material Components 库,所以我的应用程序主题有 parent Theme.MaterialComponents.DayNight

我遇到的问题是我的主题的颜色。这是一个问题的主要地方是在我定义的 DialogFragment 中。如果我像这样声明我的主题,并设置了明确的主要颜色、主要颜色和强调颜色:

<style name="DarkTheme" parent="Theme.MaterialComponents.DayNight">
    <item name="colorPrimary">@color/colorDarkPrimary</item>
    <item name="colorPrimaryDark">@color/colorDarkPrimaryDark</item>
    <item name="colorAccent">@color/colorDarkAccent</item>
</style>

那么我的 DialogFragment 的按钮是完全不可见的(它们应该是 colorAccent):在此处输入图像描述

如果我将所有颜色声明从主题中注释掉,那么按钮就会出现: 在此处输入图像描述

问题当然是我希望能够定义自己的颜色。我试过只定义 acolorPrimary而不是定义colorPrimaryDarkand colorAccent,但这会导致重音文本由于某种原因完全不可见的相同问题。

标签: androidstylesmaterial-design

解决方案


我将其保留,以便其他人可以找到它,但答案始终存在于文档中。

继承任何Theme.MaterialComponents更改您必须赋予颜色的名称。您colorAccent必须使用colorSecondary.

请参阅: https ://github.com/material-components/material-components-android/blob/master/docs/theming/Color.md

这就是问题的一半。另一半是,在使用 MaterialComponents 时,最好使用MaterialAlertDialogBuilder. 所以我将我的对话框生成器切换为这样定义:

val builder = MaterialAlertDialogBuilder(it, R.style.AlertDialogTheme)

最后一步是R.style.AlertDialogTheme声明。在styles.xml 中,我定义了该主题来设置警报对话框的样式,它看起来像这样:

<style name="AlertDialogTheme" parent="Theme.MaterialComponents.DayNight.Dialog.Alert">
    <item name="buttonBarPositiveButtonStyle">@style/AlertButton</item>
    <item name="buttonBarNegativeButtonStyle">@style/AlertButton</item>
    <item name="buttonBarNeutralButtonStyle">@style/AlertButton</item>
</style>

所做@style/AlertButton的只是将文本颜色设置为我们所追求的颜色:

<style name="AlertButton" parent="Widget.MaterialComponents.Button.TextButton">
    <item name="android:textColor">@color/colorDarkAccent</item>
</style>

最后,对话框按钮使用您想要的颜色。


推荐阅读