我目前可以使用我的基本活动中的以下内容将状态栏文本颜色从浅色更新为深色:
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 函数,但尚不清楚如何从文档中完成此操作。有人能指出我正确的方向吗?
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
可为空,因此需要 ?
检查。
WindowInsetControllerCompat
:
val windowInsetController = ViewCompat.getWindowInsetsController(window.decorView)
windowInsetController?.isAppearanceLightStatusBars = true // or false
window.decorView.windowSystemUiVisibility
的值 - 如果它包含 View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
,则意味着您的视图层次结构包含带有此标志的视图,该标志会被传播并影响 systemUiVisibility
计算。
我和其他人一样,无法获得 @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
}
}
为此有新的 API,只需 3 行代码即可制作灯光状态栏。
val windowInsetController = WindowCompat.getInsetsController(window, window.decorView)
windowInsetController.isAppearanceLightStatusBars = true
window.statusBarColor = Color.WHITE
祝你好运,