34

I search but I can't find if it's possible to change the StatusBar color for each platform, from my portable code? (for Android, iOS & WinPhone 8.1)

public App()
{
    // Change the StatusBar color
    MainPage = new MainPageUser();
}
wonea
  • 4,783
  • 17
  • 86
  • 139
Emixam23
  • 3,854
  • 8
  • 50
  • 107
  • 1
    You will have to use platform-specific code for this. [See](http://stackoverflow.com/questions/37925767/xamarin-forms-wp81-status-bar-background-color/37927870#37927870) a recent answer I wrote with regards to how to change the color on WP8.1. – Paul Jun 23 '16 at 16:16
  • Thank I'll take a look :) – Emixam23 Jun 23 '16 at 16:20
  • Do you want to change ActionBar color? – GeralexGR Jun 24 '16 at 09:40
  • I want to change the bar where the time and the batterie life are put – Emixam23 Jun 24 '16 at 10:13
  • 2
    Android: `Window.SetStatusBarColor(Android.Graphics.Color.ParseColor("#FFFFFF")); //or any other hex value` in MainActivity. On iOS statusbar color depends on the Color of Navigationbar so `MainPage = new NavigationPage(new MyPage()) { BarBackgroundColor = Color.FromHex("000000"), BarTextColor = Color.White };` would make a black navbar and satusbar with white text in the navbar. To change the textcolor in statusbar you've to set `UIStatusBarStyle UIStatusBarStyleBlackTranslucent` in info.plist – Nitro.de Jun 24 '16 at 10:23
  • 1
    `UIStatusBarStyleBlackTranslucent` means white text – Nitro.de Jun 24 '16 at 10:24
  • Thank :) What about WinPhone8.1? – Emixam23 Jun 24 '16 at 10:33
  • 1
    `var statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();` where the `StatusBar`-Class has `BackgroundColor`, `BackgroundOpacity`, `ForegroundColor` properties – Nitro.de Jun 24 '16 at 10:37
  • 1
    `statusBar.BackgroundOpacity = 1;` is important else it wont work – Nitro.de Jun 24 '16 at 10:38

10 Answers10

41

I believe you would be better off writing a little bit of platform-specific code:

For Android:

On your MainActivity.cs on the Droid project, right after

LoadApplication(new App());

of the overriden OnCreate method, add:

Window.SetStatusBarColor(Android.Graphics.Color.Argb(255, 0, 0, 0));

Like so:

protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);            
            LoadApplication(new App());
            Window.SetStatusBarColor(Android.Graphics.Color.Argb(255, 0, 0, 0)); //here
        }
lemur
  • 565
  • 6
  • 11
  • 8
    This is the correct answer. The rest require changing the color of the navigation bar - Sometimes there is no navigation bar. Note `SetStatusBarColor` is only supported in [API level 21 and up](https://developer.android.com/reference/android/view/Window.html#setStatusBarColor(int)). Therefore, we should check for this before calling SetStatusBarColor. `if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop){Window.SetStatusBarColor(...);}` – clamchoda Feb 19 '19 at 16:48
  • 1
    Thank you beautiful strangers this has been vexing me – Echostorm Nov 14 '19 at 15:05
  • What about iOS? – user1034912 Apr 13 '21 at 07:20
  • Confirming this answer still works in 2021. Semi literate C# developer, brand new to Xamarin (10 minutes lifetime experience) and this answer was not only correct but a lot less verbose than the accepted one. – IdusOrtus Apr 22 '21 at 17:57
39

I'm coming back to this answer years later to fix it because my answer had been wrong even though it had been accepted as the correct answer. I have now fixed it.

I had misread the question to want to change the navigation bar or that it worked differently in Android at that time.

I think at least this is a much better answer and should be better help to change the color of the navigationbar in Android and iOS.

Add this code to your Xamarin.Forms project

public interface IStatusBarPlatformSpecific
{
  void SetStatusBarColor(Color color);
}

add this class to your Android project

[assembly: Dependency(typeof(MyDemo.Droid.CustomRenderers.Statusbar))]
namespace MyDemo.Droid.CustomRenderers
{
    public class Statusbar : IStatusBarPlatformSpecific
    {
       public Statusbar()
       {
       }

       public void SetStatusBarColor(Color color)
       {
         // The SetStatusBarcolor is new since API 21
         if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
        {
          var androidColor = color.AddLuminosity(-0.1).ToAndroid();
         //Just use the plugin
 CrossCurrentActivity.Current.Activity.Window.SetStatusBarColor(androidColor);
         }
         else
         {
          // Here you will just have to set your 
          // color in styles.xml file as shown below.
         }
       }
   }
}

Add this CurrentActivityPlugin to your projects

Now you can change the color in your Forms project like this

var statusbar = DependencyService.Get<IStatusBarPlatformSpecific>();
statusbar.SetStatusBarColor(Color.Green);

Note the else statement above. If you are using an older buildversion than 21 you will need to hard-code your color to the styles.xml in your Android project like this

<?xml version="1.0" encoding="utf-8" ?>
<resources>
   <style name="MainTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">  
      <item name="android:statusBarColor">#544054</item>  
   </style>
</resources>

For iOS its similar

add this to your Info.plist (more docs here)

<key>UIStatusBarStyle</key>
<string>UIStatusBarStyleLightContent</string>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>

and add this code to your SetStatusBarColor ethod in the iOS version of the StatusBar class

UIView statusBar = UIApplication.SharedApplication.ValueForKey(
new NSString("statusBar")) as UIView;
 
 if (statusBar != null && statusBar.RespondsToSelector(
 new  ObjCRuntime.Selector("setBackgroundColor:")))
 {
   // change to your desired color 
   statusBar.BackgroundColor = Color.FromHex("#7f6550").ToUIColor(); 
 }

I wrote a more detailed blog post on how to set the color of the statusbar from Xamarin.Forms if somebody is interested. It does only talk about Android and iOS but should give you an idea what to do with other platforms.

Sturla
  • 3,446
  • 3
  • 39
  • 56
  • 1
    I'm trying option 1 and it does not work for me. The color remains the same default blue. – Chucky Aug 16 '18 at 14:46
  • 1
    Tried option 2 but my status bar is stuck as blue. – Chucky Aug 16 '18 at 15:03
  • 2
    AFAIK, only has effect *if* you are using NavigationBar. When NavigationBar=false, this has no effect (in my situation). – ToolmakerSteve Sep 01 '18 at 19:05
  • Upvoted for the plist bit but the other stuff not working for me – robbpriestley Nov 09 '18 at 04:08
  • 2
    What if you don't use a NavigationPage nor a NavigationBar? I – jbtamares Mar 03 '19 at 06:30
  • 3
    This is for the **navigation bar**, not the status bar, which is what the question is asking so I am surprised to see it marked as the accepted answer... but to pile on for NavigationBar... the easiest non-platform specific way is to just set an implicit style in your App.xaml: – Mark Z. Sep 01 '19 at 06:33
  • @MarkZhukovsky I updated the answer. I had answered the statusbar question also but that was on the bottom of the answer and totally not obvious. I redid the answer so now it should be correct. – Sturla Feb 27 '20 at 08:57
  • .ToAndroid() is part of "using Xamarin.Forms.Platform.Android;" – Belight Apr 03 '21 at 09:20
  • 1
    @Sturla can you update the link to the blog post (last link), it now leads to a spam page – maf-soft Mar 16 '22 at 14:44
  • 1
    Done @maf-soft! I lost my domain some time ago. Thank you for letting me know about this! – Sturla Mar 17 '22 at 12:36
28

Another option for Android: change the color in the file \Resources\values\styles.xml (Android project).

<item name="colorPrimaryDark">#00FF00</item>
Tonatio
  • 4,026
  • 35
  • 24
  • 3
    This is the only way to set the colour of the status bar in Android. In my experience, there is no way to do this in a cross platform manner in Xamarin Forms. I'd be happy to be proven wrong. – Chucky Nov 26 '18 at 18:14
  • 2
    This is the more preferred way then adding the statement: Window.SetStatusBarColor(Android.Graphics.Color.Argb(255, 0, 0, 0)); from previous answer since in this case status bar is immediately colored as desired on load and in the previous answer it is colored by default at the beginning and then redrawn. This can be very obvious if your activity loading time is not instant. – Miloš Oct 24 '20 at 14:14
  • This won't work as you need to respond to light/dark mode changes – user1034912 Apr 13 '21 at 07:20
3

Using this approach you can change it on every page.

Application.Current.MainPage.SetValue(NavigationPage.BarBackgroundColorProperty, Color.Black);
Alexander Maslew
  • 408
  • 5
  • 16
3

Maybe I'm not understanding the question, but I hope this helps.

After searching around quite a bit trying to find out how to change the iPhoneX status bar color (the bit behind the notch), I found out that it automatically sets itself based on the BackroundColorproperty of the root ContentPage.

So in Xaml it's as easy as this:

   <ContentPage.BackgroundColor>
        <OnPlatform x:TypeArguments="Color"
                    iOS="Navy"
                    Android="Yellow"
                    />
    </ContentPage.BackgroundColor>

I'm basically using the approach described in one of the answers here: https://stackoverflow.com/a/46199029/960691, but modifying it a little by giving you a code snippet that I've focused for your individual question (at least I think!)

Le Mot Juiced
  • 3,761
  • 1
  • 26
  • 46
  • This worked for me, when using iOS 11 safe area. So, my content starts below the status bar, but the background color extends over the entire page, including outside of the safe area. – ToolmakerSteve Sep 01 '18 at 19:07
0

On the latest versions of Xamarin you no longer need sketchy plugins and can instead do the following on Android:

var androidColor = color.ToAndroid();               
Xamarin.Essentials.Platform.CurrentActivity.Window.SetStatusBarColor(androidColor);

So a complete dependency example in Android:

using System;
using Android.OS;
using WikiSpiv.Droid.Extras;
using WikiSpiv.Extras;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: Dependency(typeof(Statusbar))]
namespace WikiSpiv.Droid.Extras
{
    public class Statusbar : IStatusBarPlatformSpecific
    {
        public Statusbar()
        {
        }

        public void SetStatusBarColor(Color color)
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
            {
                var androidColor = color.ToAndroid();
                Xamarin.Essentials.Platform.CurrentActivity.Window.SetStatusBarColor(androidColor);
            }
        }
    }

}

In Forms:

using System;
using Xamarin.Forms;

namespace WikiSpiv.Extras
{
    public interface IStatusBarPlatformSpecific
    {
        public void SetStatusBarColor(Color color);
    }
}

And it can be called like this:

var statusbar = DependencyService.Get<IStatusBarPlatformSpecific>();
statusbar.SetStatusBarColor(Color.Green);
Daniel Centore
  • 3,220
  • 1
  • 18
  • 39
0

Step 1. Add interface in shared class

    public interface IStatusBarColor
        {
            void changestatuscolor(string color);
        }

Step 2. on main activity inject dependency and implement the interface

[assembly: Dependency(typeof(ETCrewReport.Droid.MainActivity))]
 public class MainActivity : FormsAppCompatActivity, IStatusBarColor  
    {
      ......
      ...
      public static Context context;

        protected override void OnCreate(Bundle bundle)
        {
        }
 public void changestatuscolor(string color)
        {
            try
            {
                if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
                {
                    var c = MainActivity.context as FormsAppCompatActivity;
                    c?.RunOnUiThread(() => c.Window.SetStatusBarColor(Android.Graphics.Color.ParseColor(color)));
                }
            }
            catch (Exception ex)
            {
                 
            }

    }
    

Step 3. get the dependency in the required xaml.cs file on OnAppearing method

protected async override void OnAppearing()
        {
            try
            {
                DependencyService.Get<IStatusBarColor>().changestatuscolor(Color.Black.ToHex());
            }
            catch (Exception ex)
            {
                throw;
            }
        } 
Vega
  • 27,856
  • 27
  • 95
  • 103
Wonde_Man
  • 55
  • 6
0

in your android

MainActivity.cs

after the

LoadApplication(new App());

add this line

Window.SetStatusBarColor(Android.Graphics.Color.Argb(255, 62, 102, 226));

the color code is Argb format (Alpha,Red,Green,Blue) You can change your intensity with the alpha percentage from 0-255 below mentioned may help you with opacity of your alpha color for black with 50% alpha use Window.SetStatusBarColor(Android.Graphics.Color.Argb(80, 0, 0, 0));

  • 100% - FF
  • 95% - F2
  • 90% - E6
  • 85% - D9
  • 80% - CC
  • 75% - BF
  • 70% - B3
  • 65% - A6
  • 60% - 99
  • 55% - 8C
  • 50% - 80
  • 45% - 73
  • 40% - 66
  • 35% - 59
  • 30% - 4D
  • 25% - 40
  • 20% - 33
  • 15% - 26
  • 10% - 1A
  • 5% - 0D
  • 0% - 00
0

For android:

protected override void OnCreate(Bundle savedInstanceState)
{
    AppCompatDelegate.DefaultNightMode = AppCompatDelegate.ModeNightNo;

    TabLayoutResource = Resource.Layout.Tabbar;
    ToolbarResource = Resource.Layout.Toolbar;

    this.SetStatusBarColor(Color.FromHex("#8EC5FC").ToAndroid());

    base.OnCreate(savedInstanceState);

    Xamarin.Essentials.Platform.Init(this, savedInstanceState);
    global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

    LoadApplication(new App());
}
-1

This works for me.

In the App.xaml

 <Color x:Key="navBarRed">#AA0000</Color>
 <Color x:Key="navBarBlue">#F4721C</Color>
 <Color x:Key="navBarColour">#F4721C</Color>
 <Style TargetType="NavigationPage">
     <Setter Property="BarBackgroundColor" Value="{DynamicResource navBarColour}"/>
 </Style>

Then when you want to change the colour:

if (Condition == true)
    App.Current.Resources["navBarColour"] = App.Current.Resources["navBarBlue"];
else
    App.Current.Resources["navBarColour"] = App.Current.Resources["navBarRed"];