在 Android 11 (API 30) 中以编程方式更改状态栏文本颜色 [英] Programmatically Change Status Bar Text Color in Android 11 (API 30)

查看:139
本文介绍了在 Android 11 (API 30) 中以编程方式更改状态栏文本颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前可以使用基本活动中的以下内容将状态栏文本颜色从浅色更新为深色:

I am currently able to update the status bar text color from light to dark using the following inside my base activity:

private fun toggleStatusBarTextColor(light: Boolean) {
    // clear any existing flags
    window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE;
    if(light) {
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
    } else {
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
    }
}

systemUiVisibility 现在在 API 30 上显示已弃用,尽管已弃用的方法暂时仍将起作用,但我更愿意用更新的方法替换它们来实现此目的.我已经读到我们现在应该使用 WindowInsetsController 函数,但不清楚如何从文档中实现这一点.有人能指出我正确的方向吗?

systemUiVisibility is now showing deprecated on API 30, and although the deprecated methods will still function for the time being, I would prefer to replace them with the newer way to accomplish this. I have read that we should now use the WindowInsetsController functions, but it is not clear to be how to accomplish this from the docs. Can someone point me in the right direction?

推荐答案

对于 API 30,您可以使用 WindowInsetsController.setSystemBarsAppearance(整数外观,整数掩码):

For API 30 you can use WindowInsetsController.setSystemBarsAppearance (int appearance, int mask):

使状态栏亮起:

window.insetsController?.setSystemBarsAppearance(
        WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS,
        WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
)

清除标志:

window.insetsController?.setSystemBarsAppearance(
        0,
        WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
)

请注意,getInsetsController 可以为空,因此需要检查 ?.

Note that getInsetsController is nullable hence the ? check.

或者(对于较低的 API)您可以使用 WindowInsetControllerCompat:

Alternatively (and for lower APIs) you can use WindowInsetControllerCompat:

val windowInsetController = ViewCompat.getWindowInsetsController(window.decorView)
windowInsetController?.isAppearanceLightStatusBars = true // or false

注意:如果清除标志不起作用,请检查 window.decorView.windowSystemUiVisibility - 如果它包含 View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR 这意味着您的视图层次结构包含一个带有此标志的视图,该标志被传播并影响 systemUiVisibility 计算.

Note: if clearing flag doesn't work check value of window.decorView.windowSystemUiVisibility - if it contains View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR that means your view hierarchy contains a View with this flag which is propagated and affects systemUiVisibility calculation.

这篇关于在 Android 11 (API 30) 中以编程方式更改状态栏文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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