在 Android 中更改 PreferenceFragmentCompat 对话框背景颜色

Change PreferenceFragmentCompat dialog background color in Android

我最近开始使用 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 并且工作正常,但它破坏了一切。

所以我调查了一些 in-depth 像 EditTextPreferenceDialogFragment 这样的元素,其中大多数创建并显示了一个 AlertDialog 实例 in the same function of PreferenceDialogFragment,没有任何可能改变它风格。

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

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

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

找到了!在阅读更多 AndroidX 包后发现,默认情况下 AlertDialog.Builder 在构造函数中未指定时从属性中检索默认主题。 You can see it here

因此,解决方案是在 activity 中为对话框添加特定主题,如下所示:

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

这是结果:

Bonus tip: If you want to also setup the default theme for MaterialAlertDialogBuilder you must change de attribute materialAlertDialogTheme