1 minute read

You’ve gone to all the effort of implementing a dark (or light) theme for your latest mobile application, but your user opens the app, with their phone in dark mode, but you’re bright light theme is what’s shown, retinas have been burned!. Oh no! But fear not, it’s really easy to detect the theme that the device is currently running with Xamarin.Essentials.

Video of app

If you’re looking for some advice on implementing the different themes that we’re going to be using here, then make sure you check out my previous post on how to implement multiple themes in Xamarin.Forms, as well as switching between them.

Implementation

Using Xamarin.Essentials to detect the theme is a handy one liner.

AppTheme appTheme = AppInfo.RequestedTheme;

Running the above code will return three different results:

  • Unspecified
  • Light
  • Dark

According to the Xamarin.Essentials documentation, unspecified will only be returned when the operating system does not have a specific user interface theme to request. For example, devices running versions of iOS older than 13.0.

I’ve re-used the sample from the previous blog post about theming, to show how to set the theme when you first open the app.

Xamarin.Essentials.AppTheme theme = AppInfo.RequestedTheme;

switch (theme)
{
    case Xamarin.Essentials.AppTheme.Dark:
        AppTheme = "dark";
        Current.Resources = new DarkTheme();
        break;
    case Xamarin.Essentials.AppTheme.Light:
        AppTheme = "light";
        Current.Resources = new LightTheme();
        break;
    default:
        AppTheme = "light";
        Current.Resources = new LightTheme();
        break;
}

Notes

Unfortunately, Xamarin.Essentials doesn’t yet have an event to tell you when a theme on a phone has been changed, this could create an an issue with phones and OSes that can change the theme of the phone based on sunset or similar functionality.

As always, you can find the code for these examples here

Update (03/05/2020)

Xamarin.Forms contains an experimental feature for detecting the app theme, as well as an event that fires when the theme changes. I’ve written more about this here

If you found this content helpful, please consider sponsoring me on GitHub or alternatively buying me a coffee

Comments