系统栏保护功能简介

一旦您的应用以 SDK 35 或更高版本为目标平台,系统就会强制执行 全面屏模式。系统状态栏和手势导航栏是透明的,但三按钮导航栏是半透明的。调用 enableEdgeToEdge 以实现向后兼容性。

不过,系统默认设置可能并不适用于所有用例。如需大致了解何时考虑使用透明或 半透明系统栏,请参阅 Android 系统栏设计指南全面屏设计 指南

创建透明系统栏

如需创建透明的手势导航栏,请以 Android 15 或更高版本为目标平台,或者针对早期版本使用默认实参调用 enableEdgeToEdge()。对于 三按钮导航栏,请将 Window.setNavigationBarContrastEnforced 设置为 false,否则系统会应用半透明的保护层。

创建半透明系统栏

如需创建半透明的状态栏,请创建一个与主要内容重叠的自定义可组合项,并在插边覆盖的区域中绘制渐变。

class SystemBarProtectionSnippets : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // enableEdgeToEdge sets window.isNavigationBarContrastEnforced = true
        // which is used to add a translucent scrim to three-button navigation
        enableEdgeToEdge()

        setContent {
            MyTheme {
                // Main content
                MyContent()

                // After drawing main content, draw status bar protection
                StatusBarProtection()
            }
        }
    }
}

@Composable
private fun StatusBarProtection(
    color: Color = MaterialTheme.colorScheme.surfaceContainer,
) {
    Spacer(
        modifier = Modifier
            .fillMaxWidth()
            .height(
                with(LocalDensity.current) {
                    (WindowInsets.statusBars.getTop(this) * 1.2f).toDp()
                }
            )
            .background(
                brush = Brush.verticalGradient(
                    colors = listOf(
                        color.copy(alpha = 1f),
                        color.copy(alpha = 0.8f),
                        Color.Transparent
                    )
                )
            )
    )
}

图 1. 半透明的状态栏。

对于自适应应用,请插入与每个 窗格的颜色相匹配的自定义可组合项,如全面屏设计中所述。如需创建半透明的 导航栏,请将 Window.setNavigationBarContrastEnforced 设置为 true。