Change Status Bar color during runtime on android in Xamarin.Forms

守給你的承諾、 提交于 2019-12-11 08:40:56

问题


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.ClearFlags(WindowManagerFlags.TranslucentStatus);
    Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
    Window.SetStatusBarColor(Android.Graphics.Color.Blue);
}

but it only works in the MainActivity.cs class.

I would like to change it during runtime.


回答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();


来源:https://stackoverflow.com/questions/49522703/change-status-bar-color-during-runtime-on-android-in-xamarin-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!