调用 enableEdgeToEdge
封装了真正实现向后兼容所需的逻辑,因此是设置全屏显示的首选方式。如需了解使用 enableEdgeToEdge
实现从边缘到边缘的现代方法,请参阅 Compose 和视图文档,而不是本指南。
虽然不建议这样做,但如果您的应用必须手动设置全屏显示,您可以按以下步骤操作:
- 调用
WindowCompat.setDecorFitsSystemWindows(window, false)
。 - 将系统栏设置为透明。
- 处理边衬区。
以全屏模式布置应用
使用 WindowCompat.setDecorFitsSystemWindows(window, false)
将应用布局在系统栏后面,如以下代码示例所示:
Kotlin
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, false) }
Java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WindowCompat.setDecorFitsSystemWindows(getWindow(), false); }
更改系统栏的颜色
为 Android 14 及更低版本手动创建全屏布局时,应用还必须使系统栏透明。
您可以修改 themes.xml
文件,将状态栏和导航栏的颜色设置为透明,并更改状态栏图标颜色。
<!-- values-v29/themes.xml -->
<style name="Theme.MyApp">
<item name="android:navigationBarColor">
@android:color/transparent
</item>
<!-- Optional: set to transparent if your app is drawing behind the status bar. -->
<item name="android:statusBarColor">
@android:color/transparent
</item>
<!-- Optional: set for a light status bar with dark content. -->
<item name="android:windowLightStatusBar">
true
</item>
</style>
您可以使用 WindowInsetsControllerCompat
API 而不是 theme.xml
来控制状态栏的内容颜色。为此,请使用 setAppearanceLightNavigationBars()
函数,传入 true
可将导航栏的前景颜色更改为浅色,传入 false
可恢复为默认颜色。
Kotlin
val windowInsetsController = ViewCompat.getWindowInsetsController(window.decorView) windowInsetsController?.isAppearanceLightNavigationBars = true
Java
WindowInsetsControllerCompat windowInsetsController = ViewCompat.getWindowInsetsController(getWindow().getDecorView()); if (windowInsetsController == null) { return; } windowInsetsController.setAppearanceLightNavigationBars(true);
处理边衬区
最后,应用必须处理边衬区,以便关键界面避开系统栏和刘海屏。如需了解如何处理边衬区,请参阅 Compose 和视图文档。