如何在不使用沉浸式模式下实现带透明状态栏的全屏Activity?
实现非沉浸式下的透明状态栏(不影响导航栏)
调整主题配置
修改你的AppTheme,只针对状态栏做透明设置,全程不触碰导航栏相关属性:
<style name="AppTheme" parent="@style/Theme.MaterialComponents.DayNight.NoActionBar.Bridge"> <item name="android:colorEdgeEffect">@color/color_subtitle_text</item> <!-- 必须开启,才能自定义状态栏背景 --> <item name="android:windowDrawsSystemBarBackgrounds">true</item> <!-- 设置状态栏为完全透明 --> <item name="android:statusBarColor">@android:color/transparent</item> <!-- 可选:如果页面背景是浅色,开启这个让状态栏文字变深色,避免看不清 --> <item name="android:windowLightStatusBar">true</item> <!-- 移除原有的android:windowTranslucentStatus,这个属性会导致状态栏半透明且强制布局延伸,不符合需求 --> </style>
代码层面补充(适配多版本)
如果部分机型仍有异常,在Activity的onCreate方法中添加以下代码,确保导航栏始终保持默认状态:
// Kotlin 实现 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { window.insetsController?.run { // 强制状态栏可见,不进入沉浸式模式 show(WindowInsets.Type.statusBars()) // 导航栏保持默认可见状态 show(WindowInsets.Type.navigationBars()) // 禁止系统自动隐藏状态栏/导航栏 systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_BARS_BY_TOUCH } } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Android 10 以下版本,让布局可延伸到状态栏后方,但不触碰导航栏设置 window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN }
// Java 实现 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { WindowInsetsController controller = getWindow().getInsetsController(); if (controller != null) { controller.show(WindowInsets.Type.statusBars()); controller.show(WindowInsets.Type.navigationBars()); controller.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_BARS_BY_TOUCH); } } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); }
关键注意点
- 绝对不要添加
android:windowTranslucentNavigation或任何隐藏/半透明导航栏的属性,否则会破坏导航栏的默认状态 - 如果你的布局不需要延伸到状态栏下方,给根布局设置
android:fitsSystemWindows="true",布局会自动避开状态栏区域,同时状态栏保持透明 - 务必在不同Android版本(尤其是Android 10、11、12+)上测试,各版本的系统栏控制逻辑存在差异
内容的提问来源于stack exchange,提问作者Vijay E
相关产品推荐
相关产品推荐

