Search code examples
xamarinxamarin.formsdarkmodedisplayalert

Xamarin: Default Display Alert background colour doesn't always follow app theme


I have a Xamarin app where I use DisplayAlert() and I have noticed that it, more often than not, will display alerts in light mode, even when I am in dark mode. While debugging, I checked the values of App.Current.UserAppTheme, App.Current.RequestedTheme, AppInfo.RequestedTheme and they were all set to dark, yet my alert still displays in light mode. I don't have access to an IOS device so I'm not sure if this is only happening on Android, but that is what I'm testing with. Has anyone come across this problem and know how to fix it? Thanks in advance.


Solution

  • So I used a combination of these two resources: one and two

    In MainActivity.cs, I added the override below which forces the android theme to update with a style I added as suggested in the accepted answer of two. Note: I used AppInfo.RequestedTheme instead of Application.Current.RequestedTheme as it was usually incorrect in my case.

    public override void OnConfigurationChanged(Configuration newConfig)
    {
        base.OnConfigurationChanged(newConfig);
    
        if (Xamarin.Essentials.AppInfo.RequestedTheme == Xamarin.Essentials.AppTheme.Light)
        {
            this.SetTheme(Resource.Style.MainTheme);
            AppCompatDelegate.DefaultNightMode = AppCompatDelegate.ModeNightNo;
        }
        else
        {
            this.SetTheme(Resource.Style.NightTheme);
            AppCompatDelegate.DefaultNightMode = AppCompatDelegate.ModeNightYes;
        }
    }