Setting Android Status Bar Background & Icon Colors

Over the past few months, I have been attempting to figure out the best ways to implement a light theme and dark theme in my Hanselman.Forms app. Working closely with my friend Kym Phillpotts we came up with a very nice theme changer for Xamarin.Forms, that allowed us to change all of the colors dynamically. The result is a very nice looking application that allows the users to pick their theme or use system defaults.

One thing that bugged me in the original implementation for Android, was the status bar color that was a single dark blue color. Modern apps will set the status bar to match the background color when toggling between light and dark. Since we are allowing the user to set the theme, we must also set the color of the status bar.

This can be accomplished with the following code:

public void SetStatusBarColor(System.Drawing.Color color, bool darkStatusBarTint)
{
    if (Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.Lollipop)
        return;
        
    var activity = Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity;
    var window = activity.Window;
    window.AddFlags(Android.Views.WindowManagerFlags.DrawsSystemBarBackgrounds);
    window.ClearFlags(Android.Views.WindowManagerFlags.TranslucentStatus);
    window.SetStatusBarColor(color.ToPlatformColor());
}

This uses my Current Activity Plugin to get the Window of the app, and also Xamarin.Essentials Color Converters to set the color to light or dark.

This works really great unless I set it to a light color where the icon colors remain white.

We can also control this with the following code:

if(Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.M)
{
    var flag = (Android.Views.StatusBarVisibility)Android.Views.SystemUiFlags.LightStatusBar;
    window.DecorView.SystemUiVisibility = darkStatusBarTint ? flag : 0;
}

Now it looks beautiful, and we are in full control!

Get the code

All of the source code for Hanselman.Forms can be found on GitHub and you can watch me code live on Twitch. I also archive all the videos on my YouTube channel.