【Android】实现状态栏背景透明,系统时间/图标直接显示在页面背景上

一、核心原理(关键点)

  • 让系统状态栏背景变成透明;
  • 调整状态栏文字颜色,确保和背景区分开;
  • 让页面内容可以延伸到状态栏下方;

二、实现步骤

1、在 Activity 代码中设置

  • WindowCompat.setDecorFitsSystemWindows(window, false):页面内容可以延伸到屏幕最顶端,和状态栏重叠。
  • statusBarColor:让状态栏背景完全透明。
  • isAppearanceLightStatusBars:适配浅色背景,状态栏文字黑色。
  • isStatusBarContrastEnforced: 关闭状态栏遮罩,否则状态栏会是半透明,不是全透明。
kotlin 复制代码
...
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setStatusBarTransparent(window)
    }
    
    /**
     * 设置状态栏透明,文字黑色,覆盖在页面内容上面
     */
    fun setStatusBarTransparent(window: Window) {
        // 布局可以延伸到屏幕最顶端
        WindowCompat.setDecorFitsSystemWindows(window, false)

        // 把状态栏背景设为透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.statusBarColor = Color.TRANSPARENT
        }

        // 关闭状态栏遮罩,否则状态栏会是半透明,不是全透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            window.isStatusBarContrastEnforced = false
        }

        // 页面布局可绘制到全屏,不受状态栏、导航栏高度限制
        window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)

        // 适配浅色背景,状态栏文字黑色
        val insetsController = WindowCompat.getInsetsController(window, window.decorView)
        insetsController.isAppearanceLightStatusBars = true
    }
}

2、XML 布局中设置 fitsSystemWindows(可选)

  • 设置 fitsSystemWindows 为 false,页面内容可以顶到屏幕最顶部,和状态栏重叠。
  • 效果类似于代码实现:WindowCompat.setDecorFitsSystemWindows(window, false)。
kotlin 复制代码
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="false"> <!-- 设为false,让内容延伸到状态栏下 -->

    <!-- 你的页面背景和内容,比如渐变背景、首页标题 -->

</androidx.constraintlayout.widget.ConstraintLayout>
相关推荐
拥小抱1 小时前
Compose 知识点
android
文章永久免费只为良心1 小时前
Web应用安全与防护_第三章_日志文件包含_从一道 CTFshow 题目讲透「日志投毒型 LFI → RCE」:原理、时序陷阱与全变种攻防手册
android·网络安全·渗透测试·漏洞危害·漏洞描述·日志投毒·红队指南
AIsoft_86891 小时前
学术讲座录音如何整理?录音APP可行吗
android·iphone
Patrick在香港4 小时前
一个斜杠,把毫秒变成十几秒
android·数据库·python·性能优化·正则表达式·回溯·redos
海雅达手持终端PDA5 小时前
工业手持终端的“去手机化”演进:看海雅达如何以“同轴扫摄”终结工程妥协,重塑工业PDA新范式
android·物联网·智能手机·硬件工程·能源·制造·iot
booboosui6 小时前
删掉一个住在本机的 agent:8 处要清,顺序不能反
android
hcgeng6 小时前
Android获取崩溃日志
android
aqi006 小时前
AI编程让鸿蒙开发电子书APP更加快捷
android·华为·harmonyos·鸿蒙·harmony
GY-937 小时前
【Android】Android Studio 中的协程
android