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

Compose中实现无状态栏和导航栏的图片全屏布局方案

Compose全屏隐藏系统栏后顶部黑边问题解决方案

问题分析

你当前代码的核心问题有两点:

  1. WindowCompat.setDecorFitsSystemWindows(window, false)调用时机错误(放在了super.onCreate之前),导致窗口配置未被正确应用;
  2. Compose布局没有处理系统窗口Insets,即使隐藏了系统栏,布局仍预留了对应区域,造成顶部黑边。

修复方案

1. 调整窗口配置调用时机

将WindowCompat.setDecorFitsSystemWindows移至super.onCreate(savedInstanceState)之后,确保Activity初始化完成后再修改窗口行为。

2. 让布局填充全屏区域

使用Modifier.windowInsetsIgnoringVisibility(WindowInsets.systemBars)让Compose布局彻底忽略系统栏的占位,填充整个窗口空间。

3. 简化系统UI控制逻辑

移除重复的系统栏隐藏代码,仅保留isSystemBarsVisible = false即可同时隐藏状态栏和导航栏。

修复后代码

class MainActivity : ComponentActivity() {
    @OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 正确设置:允许内容延伸至系统栏后方
        WindowCompat.setDecorFitsSystemWindows(window, false)

        setContent {
            MyApplicationTheme {
                val systemUiController = rememberSystemUiController()
                // 隐藏状态栏和导航栏
                systemUiController.isSystemBarsVisible = false

                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color.White)
                        // 忽略系统栏Insets,布局占满整个窗口
                        .windowInsetsIgnoringVisibility(WindowInsets.systemBars)
                ) {
                    Greeting("Android")
                }
            }
        }
    }
}

补充说明

  • 若需要实现系统栏显示/隐藏的平滑动画,可参考systemUiController的animate相关扩展方法(需依赖最新的Material库);
  • 不同Android版本的系统栏行为存在差异,建议在Android 10+和Android 12+设备上分别测试。

截图1
截图2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 22:17:34