2

I have a Xamarin.Forms app being built for iOS and Android.

I'm having some difficulty in Android updating the icon colors when setting the status bar color. I have this working for API levels below 30 using the following code:

var isLight = false;

Window currentWindow = Platform.CurrentActivity.Window;

if (Color.FromHex(hexColor).Luminosity > 0.5)
{
    isLight = true;
}

currentWindow.SetStatusBarColor(androidColor);

currentWindow.DecorView.SystemUiVisibility = isLight ? (StatusBarVisibility)(SystemUiFlags.LightStatusBar) : 0;

From what I can tell, DecorView.SystemUiVisibility is deprecated in API 30, and is supposed to be replaced with window.insetsController

What I can't figure out is if/where this API is exposed in Xamarin for me to use.

I looked at this SO question: How to change the status bar color without a navigation page

and following the last answer, I attempted to use:

var lightStatusBars = isLight ? WindowInsetsControllerAppearance.LightStatusBars : 0;

currentWindow.InsetsController?.SetSystemBarsAppearance((int)lightStatusBars, (int)lightStatusBars);

but it will not build, saying Window doesn't have InsetsController

Has anyone figured this out? I definitely need to support the latest Android and this feature is killing me

Thanks in advance!

  • Welcome to SO!. If my answer helps you to solve your issue. Remember to mark the answer when you have time , it will help others who have similar issue. – Ranjit Mar 31 '21 at 00:44

2 Answers2

3

Your code looks correct. Change target framework to Android 11.0 (R). InsetsController was added in API level 30. Due to this you may receive build error.

enter image description here

 public void UpdateStatusBarColor(String color)
  {
      Window.SetStatusBarColor(Color.ParseColor(color));
      if (Build.VERSION.SdkInt >= BuildVersionCodes.R)
      {
          Window?.InsetsController?.SetSystemBarsAppearance((int)WindowInsetsControllerAppearance.LightStatusBars, (int)WindowInsetsControllerAppearance.LightStatusBars);
      }
      else
      {
          #pragma warning disable CS0618
          Window.DecorView.SystemUiVisibility = (StatusBarVisibility)SystemUiFlags.LightStatusBar;
          #pragma warning restore CS0618
      }
  }
Ranjit
  • 833
  • 8
  • 15
  • 2
    Originally this wasn't working, but I found out the reason was because Visual Studio has two locations for Build Target, one in Build > General which has the exact phrase in the answer's image and is the right one, and one in Build > Android Application, which is the first one I changed. I made sure both were set to Android 11 R and it works, Thanks Ranjit! – Gleasonator Mar 31 '21 at 02:03
0

Can you please try this in MainActivity.cs

$ Window.SetStatusBarColor(Android.Graphics.Color.Argb(255, 114, 75, 203));