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

Android Compose:如何将Topbar颜色修改为黑色或屏幕背景色?

修改Compose主题中的状态栏颜色为黑色或背景色

针对你的需求,直接修改TestTheme中SideEffect块里的状态栏相关代码即可,以下是两种方案:

方案1:固定设置为黑色

把状态栏颜色直接指定为黑色,同时调整状态栏文字颜色确保可读性:

@Composable
fun TestTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    dynamicColor: Boolean = true,
    content: @Composable () -> Unit
) {
    val colorScheme = when {
        dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
            val context = LocalContext.current
            if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
        }
        darkTheme -> DarkColorScheme
        else -> LightColorScheme
    }
    val view = LocalView.current
    if (!view.isInEditMode) {
        SideEffect {
            val window = (view.context as Activity).window
            // 设置状态栏为黑色
            window.statusBarColor = Color.Black.toArgb()
            // 黑色背景下,设置状态栏文字为浅色(白色),确保可见
            WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = true
        }
    }

    MaterialTheme(
        colorScheme = colorScheme,
        typography = Typography,
        content = content
    )
}

方案2:设置为与屏幕背景色一致

将状态栏颜色设为当前主题的背景色,同时根据背景色亮度自动调整文字颜色:

@Composable
fun TestTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    dynamicColor: Boolean = true,
    content: @Composable () -> Unit
) {
    val colorScheme = when {
        dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
            val context = LocalContext.current
            if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
        }
        darkTheme -> DarkColorScheme
        else -> LightColorScheme
    }
    val view = LocalView.current
    if (!view.isInEditMode) {
        SideEffect {
            val window = (view.context as Activity).window
            // 设置状态栏为主题背景色
            val bgColor = colorScheme.background.toArgb()
            window.statusBarColor = bgColor
            // 根据背景色亮度判断文字颜色:亮度>0.5时用深色文字,否则用浅色
            val luminance = ColorUtils.calculateLuminance(bgColor)
            WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = luminance > 0.5
        }
    }

    MaterialTheme(
        colorScheme = colorScheme,
        typography = Typography,
        content = content
    )
}

注意:使用ColorUtils需要依赖androidx.core:core-ktx,如果项目中没有引入,需要在build.gradle中添加:

implementation "androidx.core:core-ktx:1.12.0" // 版本号可根据项目调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 12:21:25