在Xamarin.Forms中的android上的运行时期间更改状态栏颜色 [英] Change Status Bar color during runtime on android in Xamarin.Forms

查看:317
本文介绍了在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();

这篇关于在Xamarin.Forms中的android上的运行时期间更改状态栏颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆