首页 > 解决方案 > 在 Android 中更改 PreferenceFragmentCompat 对话框背景颜色

问题描述

我最近开始使用PreferenceFragmentCompatMaterialComponents并注意到在暗模式下,由ListPreference之类的首选项生成的对话框总是具有奇怪的灰色 android 背景,无论我在样式中更改了多少背景属性。

奇怪颜色的图像(左侧)

这是我试过的:

<item name="android:windowBackground">@color/colorPrimaryDark</item>
<item name="android:colorBackground">@color/colorPrimaryDark</item>
<item name="android:colorBackgroundFloating">@color/colorPrimaryDark</item>

我也尝试过使用android:background并工作,但它破坏了一切。

因此,我对EditTextPreferenceDialogFragment等元素进行了深入调查,其中大多数在 PreferenceDialogFragment 的同一函数中创建并显示了一个 AlertDialog 实例,而没有任何可能更改其样式。

或者至少这是我在对该主题进行一些研究后得出的结论。

我的问题是,有没有人找到解决方法?难道我做错了什么?因为我希望这些对话框与我的应用程序主题匹配,即使它只是背景颜色。

顺便说一句,对不起,如果之前已经回答过。我也在这里搜索过,但没有找到任何不同问题的类似答案,但没有结果。谢谢。

标签: javaandroidmaterial-designandroid-themepreferenceactivity

解决方案


找到了!在阅读更多AndroidX包后发现,默认情况下,AlertDialog.Builder在构造函数中未指定时从属性中检索默认主题。在这里你可以看到它

因此,一种解决方案是为活动中的对话框添加特定主题,如下所示:

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <item name="alertDialogTheme">@style/AlertDialogCustom</item>
</style>

然后你设置你的对话框主题,如:

<style name="AlertDialogCustom" parent="Theme.AppCompat.Light.Dialog">
    <item name="colorAccent">#FFC107</item>
    <item name="android:textColorPrimary">#FFFFFF</item>
    <item name="android:background">#4CAF50</item>
</style>

这是结果:

完全改变对话主题

额外提示:如果您还想为 MaterialAlertDialogBu ​​ilder 设置默认主题,您必须更改 de 属性 materialAlertDialogTheme


推荐阅读