简体   繁体   中英

Xamarin Forms How to change Android status bar icon color in API 30 (Android 11)

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!

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.

在此处输入图像描述

 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
      }
  }

Can you please try this in MainActivity.cs

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM