androidxamarin

Android SetDecorFitsSystemWindows changes status bar to black on resume


So I'm using Window.SetDecorFitsSystemWindows(false) in onCreate to make my app full screen, the status bar is semi-transparent drawn over my view/activity (which is what I want).

However when I change apps and then switch back to my app, the status bar turns black and my view/activity moves down a little. How do I prevent the status bar changing? I tried calling Window.SetDecorFitsSystemWindows(false) in onResume too but it doesn't make a difference.

I'm using Xamarin if that makes a difference.


Solution

  • This solved my problem for me.

    private void ApplyFullScreen()
    {
        if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.P)
            Window.Attributes.LayoutInDisplayCutoutMode |= LayoutInDisplayCutoutMode.ShortEdges;
    
        if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.R)
        {
            Window.SetDecorFitsSystemWindows(false);
            WindowCompat.SetDecorFitsSystemWindows(Window, false);
            var insets = WindowCompat.GetInsetsController(Window, Window.DecorView);
            if (insets != null)
            {
                insets.Hide(WindowInsetsCompat.Type.StatusBars());
                insets.Hide(WindowInsetsCompat.Type.NavigationBars());
                insets.SystemBarsBehavior = WindowInsetsControllerCompat.BehaviorShowTransientBarsBySwipe;
            }
        }
        else
        {
            Window.DecorView.SystemUiFlags = SystemUiFlags.LayoutStable
                | SystemUiFlags.LayoutHideNavigation
                | SystemUiFlags.LayoutFullscreen
                | SystemUiFlags.HideNavigation
                | SystemUiFlags.Fullscreen
                | SystemUiFlags.ImmersiveSticky;
        }
    }
    
    protected override void OnResume()
    {
        base.OnResume();
        ApplyFullScreen();
    }
    
    public override void OnWindowFocusChanged(bool hasFocus)
    {
        base.OnWindowFocusChanged(hasFocus);
        if (hasFocus)
        {
            ApplyFullScreen();
        }
    }