在Xamarin.Forms中的android上的运行时期间更改状态栏颜色

问题描述:

我想在运行时以编程方式更改状态栏的颜色.我已经尝试过了:

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

但是它只能在MainActivity.cs类中使用.

but it only works in the MainActivity.cs class.

我想在运行时进行更改.

I would like to change it during runtime.

依赖接口:

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

您需要可以通过多种方法获得的当前Activity的上下文; MainActivity上的静态变量,使用CurrentActivityPlugin等. hackie并使用静态变量,因此添加一个静态Context变量并将其设置在OnResume中.

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.

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

Android依赖关系实现:

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

}

用法:

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

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

statusBarColor?.CoreMeltDown();