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

nin*_*edt 6 java android android-theme kotlin android-statusbar

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

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Paw*_*wel 10

对于 API 30,您可以使用WindowInsetsController.setSystemBarsAppearance (int appearance, int mask)

要使状态栏亮起:

window.insetsController?.setSystemBarsAppearance(
        WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS,
        WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
)
Run Code Online (Sandbox Code Playgroud)

清除标志:

window.insetsController?.setSystemBarsAppearance(
        0,
        WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
)
Run Code Online (Sandbox Code Playgroud)

请注意,它getInsetsController可以为空,因此需要进行?检查。

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

val windowInsetController = ViewCompat.getWindowInsetsController(window.decorView)
windowInsetController?.isAppearanceLightStatusBars = true // or false
Run Code Online (Sandbox Code Playgroud)

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

  • 无法将文本设置为白色 (3认同)

Sam*_*ami 8

我和其他人一样,无法获得@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
    }
}
Run Code Online (Sandbox Code Playgroud)