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

迁移到Material Design主题后如何实现透明状态栏效果

适配方案

1. 布局属性配置(针对CollapsingToolbarLayout场景优先使用)

在对应页面的XML布局中做如下修改即可直接实现折叠时自动切换状态栏颜色:

  • 给外层CoordinatorLayout添加android:fitsSystemWindows="true"
  • 给AppBarLayout添加android:fitsSystemWindows="true"
  • 给CollapsingToolbarLayout添加属性:
    android:fitsSystemWindows="true"
    app:statusBarScrim="@color/colorPrimaryDark"
    
    其中statusBarScrim设置的就是工具栏完全折叠后状态栏要显示的颜色,和你基础主题里的colorPrimaryVariant保持一致即可。

2. 代码动态控制(通用多场景适配)

如果还有其他需要动态切换状态栏颜色的场景,或者需要更精细的控制,可以监听AppBar的折叠状态修改窗口属性:

// Kotlin 示例
appBarLayout.addOnOffsetChangedListener { _, offset ->
    val isCollapsed = Math.abs(offset) >= appBarLayout.totalScrollRange
    window.statusBarColor = if (isCollapsed) {
        ContextCompat.getColor(this, R.color.colorPrimaryDark)
    } else {
        Color.TRANSPARENT
    }
}
// Java 示例
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int offset) {
        boolean isCollapsed = Math.abs(offset) >= appBarLayout.getTotalScrollRange();
        if (isCollapsed) {
            getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
        } else {
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }
});

3. 主题配置修正

你出现默认蓝色状态栏的原因是MDC主题默认未自定义的colorPrimaryVariant会使用Material Design默认蓝色,先确认你的colors.xml中已经正确定义了colorPrimaryDark的自定义色值。另外可以给透明状态栏主题补充适配配置:

<style name="AppTheme.TransparentStatusBar">
    <item name="android:statusBarColor">@android:color/transparent</item>
    <!-- 根据你的需求调整状态栏文字图标颜色,亮色模式设为true,暗色模式设为false -->
    <item name="android:windowLightStatusBar">true</item>
</style>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 03:15:02