I recently started working with PreferenceFragmentCompat and MaterialComponents and noticed that in Dark mode, Dialogs generated by preferences like ListPreference always have that weird grey android background no matter how many background attributes I change in the style.
(source: pocketnow.com)
This I’ve tried:
<item name="android:windowBackground">@color/colorPrimaryDark</item> <item name="android:colorBackground">@color/colorPrimaryDark</item> <item name="android:colorBackgroundFloating">@color/colorPrimaryDark</item>
I’ve also tried with android:background and worked but it brokes everything.
So I investigated a bit in-depth at elements like EditTextPreferenceDialogFragment and most of them create and show an AlertDialog instance in the same function of PreferenceDialogFragment without any possibility to change its style.
Or at least that’s the conclusion I’ve come to after some research on the subject.
My question is, has anyone found a workaround for this? Am I doing something wrong? Cause I would like to have those dialogs matching my app theme even if it’s just the background color.
Btw, sorry if it has been already answered before. I also searched in here but found nothing and similar answers for different problems without results. Thanks.
Advertisement
Answer
Found it! After reading more the AndroidX package found that by default the AlertDialog.Builder retrieves a default theme from an attribute when no specified in the constructor. You can see it here
So a solution would be to add a specific theme for dialogs in the activity like this:
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar"> <item name="alertDialogTheme">@style/AlertDialogCustom</item> </style>
And then you setup your dialog theme like:
<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>
And this is the result:
Bonus tip: If you want to also setup the default theme for MaterialAlertDialogBuilder you must change de attribute materialAlertDialogTheme