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

Android开发如何隐藏状态栏并将内容绘制到状态栏区域

Android 全屏沉浸式(内容铺满系统栏区域+隐藏系统栏)实现方案

你遇到的两个API效果互斥问题,是系统默认的系统栏交互配置和调用顺序错误导致的,按以下步骤配置即可实现目标效果:

  • 所有代码放在Activity的onCreate方法中、setContentView()调用前执行,必须先开启边到边绘制配置,再操作系统栏隐藏逻辑,顺序颠倒会触发系统默认的布局适配逻辑,抵消边到边绘制效果。

如果你使用Kotlin开发,参考如下代码:

// 开启边到边绘制,允许内容延伸到系统栏区域
WindowCompat.setDecorFitsSystemWindows(window, false)

// 获取系统栏控制器,配置隐藏规则
val insetsController = WindowCompat.getInsetsController(window, window.decorView)
insetsController.apply {
    // 配置隐藏后的交互逻辑:仅从屏幕边缘滑动时临时显示系统栏,无操作后自动隐藏,不会挤压布局
    systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
    // 同时隐藏状态栏、导航栏两类系统栏
    hide(WindowInsetsCompat.Type.systemBars())
}

// 清除系统栏默认背景,避免系统预留占位
window.statusBarColor = android.graphics.Color.TRANSPARENT
window.navigationBarColor = android.graphics.Color.TRANSPARENT

如果你使用Java开发,参考如下代码:

// 开启边到边绘制
WindowCompat.setDecorFitsSystemWindows(getWindow(), false);

// 配置系统栏隐藏逻辑
WindowInsetsControllerCompat insetsController = WindowCompat.getInsetsController(getWindow(), getWindow().getDecorView());
insetsController.setSystemBarsBehavior(WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
insetsController.hide(WindowInsetsCompat.Type.systemBars());

// 设置系统栏透明
getWindow().setStatusBarColor(android.graphics.Color.TRANSPARENT);
getWindow().setNavigationBarColor(android.graphics.Color.TRANSPARENT);

避坑说明

  • 不要在布局的任意节点添加android:fitsSystemWindows="true"属性,该属性会自动给控件添加等于系统栏高度的内边距,直接导致内容无法延伸到原系统栏区域。
  • 后续如果需要临时唤起系统栏,直接调用insetsController.show(WindowInsetsCompat.Type.systemBars())即可,不要修改setDecorFitsSystemWindows的取值,否则会再次出现布局被挤压的问题。
  • 不要在Android Studio布局预览中验证效果,预览环境对窗口边衬的模拟存在已知偏差,必须在真机/官方模拟器上运行测试。
  • 如果你使用Jetpack Compose开发,只需要在Activity中保留上述Window配置即可,Compose容器默认支持边到边绘制,不需要额外给布局添加边距处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 09:57:30