A friend reached out today and asked âHey, I need my splash screen to be themed based on whether Dark Mode is selected on the Android device.â I had never done that before, so I was curious how it should be done.
Dark Mode is new to Android 10, a.k.a. Android Q. Not as tasty, but hey, gotta ship something. It has a range of benefits, such as lower energy consumption, looking cool, and frustrating developers without budget for theme-aware apps.
It turns out, after some sleuthing, itâs relatively straightforward.
First, this article assumes youâre following the âsplash screen as a themeâ approach, which you can learn more about here. The example is for Xamarin.Forms, but the same approach applies to regular Android development.
Basically, you have a âsplashscreenâ style, and you set it as your appâs theme in the Android manifest. Then, you âswapâ to the real theme in MainActivity. For example, what I use in an app, located in resources/values/styles.xml:
<!-- Splash screen style --> <style name="splashscreen" parent="Theme.AppCompat.DayNight"> <item name="android:windowBackground">@drawable/splash</item> <item name="android:windowNoTitle">true</item> <item name="android:windowIsTranslucent">false</item> <item name="android:windowIsFloating">false</item> <item name="android:backgroundDimEnabled">true</item> </style>
Note my drawable. I want a different drawable for my dark vs. light (normal) theme. Hereâs what is different:
- The parent is now Theme.AppCompat.DayNight
- Iâve added a different set of drawable folders for the Dark theme images. These are the same folder names, with -night appended to the end:
In this example, I havenât yet added the other folder variations, but you get the point.
The theme swap code in MainActivity is as follows:
protected override void OnCreate(Bundle savedInstanceState)
{ TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; // Swap back to the normal app theme. We used Splash so we didn't have to create a special activity. // Cute hack, and better approach. // Idea from URL: https://xamarinhelp.com/creating-splash-screen-xamarin-forms/ Window.RequestFeature(WindowFeatures.ActionBar); SetTheme(Resource.Style.MainTheme);
Thatâs all there is to it. If Dark mode is enabled, the splash.png from the -night folder will be used, otherwise the normal image will takes its rightful place.
If you have any questions, please hit me up in the comments.
Special thanks to this StackOverflow article for the ânight hint.
More info on Android Dark Theme can be found here.