Skip to content Skip to sidebar Skip to footer

Change Status Bar Color During Runtime On Android In Xamarin.forms

I would like to change the colour of the status bar during run-time programatically. I have tried this: if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop) { Window.Clea

Solution 1:

Dependency Interface:

public interface IStatusBarColor
{
    void CoreMeltDown();
    void MakeMe(string color);
}

You need the current Activity's context which you can obtain via multiple methods; A static var on the MainActivity, using the CurrentActivityPlugin, etc... Lets keep it simple & hackie and use a static var, so add a static Context var and set it in the OnResume.

MainActivity Context

    public static Context context;
    protected override void OnResume()
    {
        context = this;
        base.OnResume();
    }

Android Dependency Implementation:

public class StatusBarColor : IStatusBarColor
{
    public void MakeMe(string color)
    {
        if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
        {
            var c = MainActivity.context as FormsAppCompatActivity;
            c?.RunOnUiThread(() => c.Window.SetStatusBarColor(Color.ParseColor(color)));
        }
    }

    public void CoreMeltDown()
    {
        Task.Run(async () =>
        {
            for (int i = 0; i < 10; i++)
            {
                switch (i%2)
                {
                    case 0:
                        MakeMe($"#{Integer.ToHexString(Color.Red.ToArgb())}");
                        break;
                    case 1:
                        MakeMe($"#{Integer.ToHexString(Color.White.ToArgb())}");
                        break;
                }
                await Task.Delay(200);
            }
        });
    }

}

Usage:

var statusBarColor = DependencyService.Get<IStatusBarColor>();

statusBarColor?.MakeMe(Color.Blue.ToHex());

statusBarColor?.CoreMeltDown();

Post a Comment for "Change Status Bar Color During Runtime On Android In Xamarin.forms"