一、核心原理(关键点)
- 让系统状态栏背景变成透明;
- 调整状态栏文字颜色,确保和背景区分开;
- 让页面内容可以延伸到状态栏下方;
二、实现步骤
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>