以编程方式更改 Android 11 (API 30) 中的状态栏文本颜色

问题描述 投票:0回答:3

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

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 函数,但尚不清楚如何从文档中完成此操作。有人能指出我正确的方向吗?

java android kotlin android-theme android-statusbar
3个回答
9
投票

对于 API 30,您可以使用

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
可为空,因此需要
?
检查。

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

WindowInsetControllerCompat
:

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

注意:如果清除标志不起作用,请检查

window.decorView.windowSystemUiVisibility
的值 - 如果它包含
View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
,则意味着您的视图层次结构包含带有此标志的视图,该标志会被传播并影响
systemUiVisibility
计算。


7
投票

我和其他人一样,无法获得 @Pawel 建议在所有 Android 操作系统版本上使用的新 API。不幸的是,我发现我必须同时使用旧版 API 和新版 API 才能使其在 Android 11 及以下版本上运行:

fun setStatusBarLightText(window: Window, isLight: Boolean) {
    setStatusBarLightTextOldApi(window, isLight)
    setStatusBarLightTextNewApi(window, isLight)
}


private fun setStatusBarLightTextOldApi(window: Window, isLight: Boolean) {
    val decorView = window.decorView
    decorView.systemUiVisibility =
        if (isLight) {
            decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
        } else {
            decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        }
}

private fun setStatusBarLightTextNewApi(window: Window, isLightText: Boolean) {
    ViewCompat.getWindowInsetsController(window.decorView)?.apply {
        // Light text == dark status bar
        isAppearanceLightStatusBars = !isLightText
    }
}

0
投票

为此有新的 API,只需 3 行代码即可制作灯光状态栏。

val windowInsetController = WindowCompat.getInsetsController(window, window.decorView)
    windowInsetController.isAppearanceLightStatusBars = true
    window.statusBarColor = Color.WHITE

祝你好运,

© www.soinside.com 2019 - 2024. All rights reserved.