You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中实现浅色导航栏与状态栏的非废弃方案咨询

Kotlin中替代废弃API实现浅色状态栏与导航栏的方案

嘿,刚好我对这个废弃API的替代方案很熟悉,来给你捋清楚~

你之前的代码确实能正常运行,但从Android 11(API 30)开始,systemUiVisibility以及对应的SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR、SYSTEM_UI_FLAG_LIGHT_STATUS_BAR都被标记为废弃了,官方推荐用WindowInsetsControllerCompat(来自androidx.core库)来替代,写法更直观还能兼容低版本。

完整的替代实现代码

val window = this@MainActivity.window

// 保留原来的状态栏、导航栏颜色设置,这部分没有废弃
window.statusBarColor = ContextCompat.getColor(this@MainActivity, R.color.white)
window.navigationBarColor = ContextCompat.getColor(this@MainActivity, R.color.white)

// 用WindowInsetsControllerCompat替代废弃的systemUiVisibility
val insetsController = WindowInsetsControllerCompat(window, window.decorView)
// 开启浅色状态栏模式(让状态栏的文字、图标变成深色,适配白色背景)
insetsController.isAppearanceLightStatusBars = true
// 开启浅色导航栏模式(让导航栏的按钮图标变成深色,适配白色背景)
insetsController.isAppearanceLightNavigationBars = true

补充说明

  • 这个方案依赖androidx.core库,如果你的项目还没引入,需要在模块的build.gradle(或build.gradle.kts)中添加依赖:
    implementation "androidx.core:core-ktx:1.12.0" // 可以替换成最新版本
    
  • WindowInsetsControllerCompat会自动处理版本兼容,不用单独写API判断逻辑,比原来的写法更简洁可靠。

内容的提问来源于stack exchange,提问作者Amy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:08:45