文档管理中心
开发与测试开放能力API应用框架ArkUI(方舟UI框架)窗口管理窗口基础能力窗口沉浸式

窗口沉浸式

场景介绍

窗口沉浸式指通过优化应用界面,使内容成为视觉焦点,以最大限度排除无关元素的干扰,实现沉浸式效果。其实现需针对不同设备的屏幕特性、交互逻辑及系统规范进行差异化适配。

沉浸式效果

通常情况下,影音类、游戏类、办公类等应用为了尽可能全屏显示,减少其他无关界面元素的干扰,会主动调整系统界面元素的显隐状态或样式来聚焦更多应用界面内容。

开发应用沉浸式效果主要通过调整状态栏、应用界面和底部导航区域的显示效果来减少状态栏和导航区域等系统界面的突兀感,从而使用户获得最佳的UI体验。

开发者可以通过三种方式实现应用界面内的沉浸式效果:

  • 隐藏系统界面元素,使应用内容布满整个窗口显示区域。

  • 设置窗口为沉浸式布局,将应用内容拓展到整个窗口显示区域,通过布局避让避免重要组件与系统界面元素重叠。

  • 使用组件安全区域能力,将部分组件拓展到安全区域外部。该方案下,界面元素仅做绘制延伸,无法单独布局到状态栏和导航区域,针对需要单独布局UI元素到系统界面元素区域的场景,建议使用上述两种方案。

界面元素构成

典型全屏应用窗口包括系统界面元素和应用界面。其中系统界面元素包含状态栏和导航区域,通常在沉浸式布局下称为避让区域,避让区域之外的区域称为安全区域。

沉浸式布局

沉浸式布局是一种让应用可布局区域拓展至整个窗口显示区域的状态。

  • 非沉浸式布局下,应用界面内容默认会避开系统UI的显示区域,包括状态栏、导航区域。

  • 沉浸式布局下,应用内的可用布局区域延伸到整个窗口大小,此时应用界面的布局内容可与系统UI界面重叠显示,但系统界面元素层级始终高于应用界面内容。

    可以通过isImmersiveLayout()接口判断当前窗口是否为沉浸式布局。

多设备场景下不同窗口形态的沉浸式开发与实现可以参考窗口沉浸式最佳实践。

说明

沉浸式布局是窗口内元素的布局方式,进入或退出沉浸式布局不会改变窗口尺寸和位置,仅会影响应用界面内元素的布局。

自由窗口状态和非自由窗口状态下实现沉浸式布局的方式不同。

  • 非自由窗口状态下,可通过使用setWindowLayoutFullScreen()setImmersiveModeEnabledState()接口设置当前窗口进入/退出窗口沉浸式布局。

    说明

    非自由窗口状态下,除应用子窗外的其他类型窗口在创建时默认为非沉浸式布局,子窗口创建后默认为沉浸式布局。

    收起
    自动换行
    深色代码主题
    复制
    1. import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
    2. import { hilog } from '@kit.PerformanceAnalysisKit';
    3. import { window } from '@kit.ArkUI';
    4. const DOMAIN = 0x0000;
    5. export default class EntryAbility extends UIAbility {
    6. // ...
    7. onWindowStageCreate(windowStage: window.WindowStage): void {
    8. windowStage.loadContent('pages/Index', async (err) => {
    9. if (err.code) {
    10. return;
    11. }
    12. try {
    13. const mainWindow: window.Window = windowStage.getMainWindowSync(); // 获取应用主窗口
    14. await mainWindow.setWindowLayoutFullScreen(true); // 进入窗口沉浸式布局(非自由窗口状态)
    15. mainWindow.setWindowDecorVisible(false); // 隐藏窗口标题栏,进入沉浸式布局(自由窗口状态)
    16. } catch (e) {
    17. console.error(`Failed to set status bar to invisible`);
    18. }
    19. });
    20. }
    21. // ...
    22. }
    展开
    非自由窗口的非沉浸式布局示意 非自由窗口的沉浸式布局示意
  • 自由窗口状态下,可通过setWindowDecorVisible()接口控制窗口标题栏显隐,当标题栏隐藏时,窗口处于沉浸式布局。

    展开
    自由窗口的非沉浸式布局示意 自由窗口的沉浸式布局示意

布局避让

沉浸式布局状态下,窗口可布局区域与系统界面元素的显示区域可以重叠,此时为了避免状态栏、导航区域等系统界面元素交叉导致应用界面显示被遮挡,需要在组件布局时做额外的布局避让。

窗口与系统界面元素显示的交叉区域称为避让区域,应用内通过布局避让,将关键显示组件避开避让区域显示,从而达到沉浸式效果。

系统支持的避让区域类型通过枚举AvoidAreaType表示。

避让区域AvoidArea的计算方式

避让区域AvoidArea的数据结构如下所示:

收起
自动换行
深色代码主题
复制
  1. interface AvoidArea {
  2. visible: boolean;
  3. leftRect: Rect;
  4. topRect: Rect;
  5. rightRect: Rect;
  6. bottomRect: Rect;
  7. }
  8. interface Rect {
  9. left: number;
  10. top: number;
  11. width: number;
  12. height: number;
  13. }
  • 其中包含四组Rect信息,表示此类型的避让区域在相对于窗口中心点的方向和具体矩形区域位置。

  • visible属性不代表任何系统UI的可见性,没有实际含义,请避免使用此属性

在避让区域的计算中,将窗口按照对角线分为四个三角形区域,当对应系统界面元素的位置(矩形中心点)落于某个方向上的三角形区域时,提供的避让区域将在对应的Rect中。如下图所示整个矩形为窗口区域,以窗口左上角为原点,水平向右为X轴正方向,垂直向下为Y轴正方向,窗口矩形的两条对角线将整个矩形划分为四个方向上的Rect区域,用以表示避让区域相对窗口的几何位置。

其中每个Rect为(X, Y, Width, Height)构成的四元组,表示以窗口左上角为原点的唯一矩形区域。

如下图,挖孔区域表示为 [topRect, (x1, y1, w1, h1)] ,底部导航区域表示为 [bottomRect, (0, H-h2, W, h2)]

隐藏系统界面元素实现沉浸式效果

可通过隐藏系统界面元素实现沉浸式效果,适用于游戏、电影等应用场景。例如,在相机大图页面隐藏状态栏以获得沉浸式的图片查看效果。

说明

setSpecificSystemBarEnabled()setWindowSystemBarEnable()等控制系统界面元素显示的接口仅非自由窗口状态下的主窗口支持调用,在辅助窗口中调用或自由窗口状态下调用不生效。在主窗口非全屏/非最大化模式时调用不会立即生效,应用在进入全屏/最大化模式后配置生效。

  1. 调用setWindowLayoutFullScreen()接口设置窗口进入沉浸式布局。

  2. 调用setSpecificSystemBarEnabled()隐藏状态栏。

收起
自动换行
深色代码主题
复制
  1. import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
  2. import { hilog } from '@kit.PerformanceAnalysisKit';
  3. import { window } from '@kit.ArkUI';
  4. const DOMAIN = 0x0000;
  5. export default class EntryAbility extends UIAbility {
  6. // ...
  7. onWindowStageCreate(windowStage: window.WindowStage): void {
  8. windowStage.loadContent('pages/Index', async (err) => {
  9. if (err.code) {
  10. return;
  11. }
  12. try {
  13. const mainWindow: window.Window = windowStage.getMainWindowSync(); // 获取应用主窗口
  14. await mainWindow.setWindowLayoutFullScreen(true); // 设置窗口进入沉浸式
  15. await mainWindow.setSpecificSystemBarEnabled('status', false); // 设置状态栏隐藏
  16. } catch (e) {
  17. console.error(`Failed to set status bar to invisible`);
  18. }
  19. });
  20. }
  21. // ...

适配沉浸式布局实现沉浸式效果

说明

全局悬浮窗、模态窗口和系统窗口本身不具备获取避让区域的能力,如果需要在这些窗口中适配布局避让,需要使用setSystemAvoidAreaEnabled()接口使能避让区域能力后再进行布局避让。

  1. 调用setWindowLayoutFullScreen()接口设置窗口进入沉浸式布局。

  2. 获取并监听窗口避让区域,在避让区域更新时同时更新应用内布局。

    此处以获取并监听状态栏、底部导航区域、挖孔区为例。

    • 可以通过使用getWindowAvoidArea()接口获取当前窗口避让区域。使用on('avoidAreaChange')接口监听避让区域的动态变化。

      常见的触发避让区域回调的场景如下:应用窗口在全屏模式、悬浮模式、分屏模式之间的切换;应用窗口旋转;多折叠设备在屏幕折叠态和展开态之间的切换;应用窗口在多设备之间的流转。

      收起
      自动换行
      深色代码主题
      复制
      1. import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
      2. import { hilog } from '@kit.PerformanceAnalysisKit';
      3. import { window } from '@kit.ArkUI';
      4. const DOMAIN = 0x0000;
      5. export default class EntryAbility extends UIAbility {
      6. // ...
      7. private async initializeMainWindow(windowStage: window.WindowStage): Promise<void> {
      8. try {
      9. this.mainWindow = windowStage.getMainWindowSync();
      10. AppStorage.setOrCreate('mainWindow', this.mainWindow);
      11. await this.mainWindow.setWindowLayoutFullScreen(true);
      12. this.initSafeArea(this.mainWindow);
      13. this.mainWindow.on('avoidAreaChange', (option) => {
      14. switch (option.type) {
      15. // 监听状态栏避让区域
      16. case window.AvoidAreaType.TYPE_SYSTEM: {
      17. const topHeight = Math.max(option.area.topRect.height, AppStorage.get<number>('topAvoidHeight') ?? 0);
      18. AppStorage.setOrCreate('topAvoidHeight', topHeight);
      19. break;
      20. }
      21. // 监听挖孔区避让区域
      22. case window.AvoidAreaType.TYPE_CUTOUT: {
      23. this.handleCutoutAvoidArea(option.area);
      24. break;
      25. }
      26. // 监听底部导航区避让区域
      27. case window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR: {
      28. const bottomHeight = Math.max(option.area.bottomRect.height, AppStorage.get<number>('bottomAvoidHeight') ?? 0);
      29. AppStorage.setOrCreate('bottomAvoidHeight', bottomHeight);
      30. break;
      31. }
      32. default: {
      33. break;
      34. }
      35. }
      36. });
      37. } catch (err) {
      38. hilog.error(DOMAIN, 'testTag', 'Failed to initialize avoid area listener. Cause: %{public}s', JSON.stringify(err));
      39. }
      40. }
      41. private initSafeArea(win: window.Window): void {
      42. try {
      43. // 获取状态栏避让区域
      44. const systemAvoidArea = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
      45. // 获取底部导航区避让区域
      46. const navigationAvoidArea = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
      47. // 获取挖孔区避让区域
      48. const cutoutAvoidArea = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_CUTOUT);
      49. AppStorage.setOrCreate('topAvoidHeight', systemAvoidArea.topRect.height);
      50. AppStorage.setOrCreate('bottomAvoidHeight', navigationAvoidArea.bottomRect.height);
      51. AppStorage.setOrCreate('leftAvoidWidth', 0);
      52. AppStorage.setOrCreate('rightAvoidWidth', 0);
      53. this.handleCutoutAvoidArea(cutoutAvoidArea);
      54. } catch (err) {
      55. hilog.error(DOMAIN, 'testTag', 'Failed to init safe area. Cause: %{public}s', JSON.stringify(err));
      56. }
      57. }
      58. private handleCutoutAvoidArea(cutoutAvoidArea: window.AvoidArea): void {
      59. if (cutoutAvoidArea.topRect.height > 0) {
      60. const topHeight = Math.max(AppStorage.get<number>('topAvoidHeight') ?? 0, cutoutAvoidArea.topRect.height);
      61. AppStorage.setOrCreate('topAvoidHeight', topHeight);
      62. }
      63. if (cutoutAvoidArea.bottomRect.height > 0) {
      64. const bottomHeight = Math.max(AppStorage.get<number>('bottomAvoidHeight') ?? 0, cutoutAvoidArea.bottomRect.height);
      65. AppStorage.setOrCreate('bottomAvoidHeight', bottomHeight);
      66. }
      67. if (cutoutAvoidArea.leftRect.width > 0) {
      68. AppStorage.setOrCreate('leftAvoidWidth', cutoutAvoidArea.leftRect.width);
      69. }
      70. if (cutoutAvoidArea.rightRect.width > 0) {
      71. AppStorage.setOrCreate('rightAvoidWidth', cutoutAvoidArea.rightRect.width);
      72. }
      73. }
      74. }
    • 还可以使用响应式环境变量装饰器@Env来实现避让区域的获取和监听。

      可通过响应式环境变量装饰器@Env(@Env(SystemProperties.WINDOW_AVOID_AREA)或@Env(SystemProperties.WINDOW_AVOID_AREA_PX))获取并监听当前窗口的避让区域信息。

      当避让区域因横竖屏切换、系统栏显隐、窗口形态变化等发生变化时,@Env变量会自动更新,并触发相关组件刷新,从而实现沉浸式布局的动态适配。示例代码如下:

      收起
      自动换行
      深色代码主题
      复制
      1. import { window } from '@kit.ArkUI';
      2. import { hilog } from '@kit.PerformanceAnalysisKit';
      3. const DOMAIN = 0x0000;
      4. @Entry
      5. @Component
      6. struct Index {
      7. @Env(SystemProperties.WINDOW_AVOID_AREA) avoidAreasVp: window.UIEnvWindowAvoidAreaInfoVP;
      8. @StorageProp('topAvoidHeight')
      9. topAvoidHeight: number = 0;
      10. @StorageProp('bottomAvoidHeight')
      11. bottomAvoidHeight: number = 0;
      12. @StorageProp('leftAvoidWidth')
      13. leftAvoidWidth: number = 0;
      14. @StorageProp('rightAvoidWidth')
      15. rightAvoidWidth: number = 0;
      16. @StorageLink('mainWindow')
      17. mainWindow: window.Window | undefined = undefined;
      18. // ...
      19. }
  3. 布局中的系统界面元素需要避让状态栏和导航区域,否则可能产生UI元素重叠等情况。

    说明

    避让区域存在大小为0的情况,当获取到的避让区域为0时,开发者需注意针对性适配此时的页面区域和布局,避免贴边、内容裁剪等问题,以确保应用界面正常显示且具有良好的美观性。

    开发者可以通过添加padding或添加占位组件的方式避让系统界面元素,此处以添加padding为例(具体数值为避让高度+10vp,防止在系统界面元素隐藏时布局内容贴边,开发者可以根据实际需求更改)。对控件顶部设置padding,实现对状态栏的避让;对底部设置padding,实现对底部导航区域的避让;对左右两侧设置padding,实现对挖孔区域的避让。

    • 避让使用getWindowAvoidArea接口获取到的避让区域的示例代码如下:

      收起
      自动换行
      深色代码主题
      复制
      1. import { window } from '@kit.ArkUI';
      2. import { hilog } from '@kit.PerformanceAnalysisKit';
      3. const DOMAIN = 0x0000;
      4. @Entry
      5. @Component
      6. struct Index {
      7. // ...
      8. build() {
      9. Column() {
      10. // 避让顶部和挖孔区域
      11. Row() {
      12. Text('Top Container')
      13. .fontSize(40)
      14. .textAlign(TextAlign.Center)
      15. .width('100%')
      16. }
      17. .backgroundColor('#2786d9')
      18. .padding({
      19. top: this.getUIContext().px2vp(this.topAvoidHeight) + 10,
      20. bottom: 10,
      21. // 避让挖孔区域
      22. left: this.getUIContext().px2vp(this.leftAvoidWidth),
      23. right: this.getUIContext().px2vp(this.rightAvoidWidth)
      24. })
      25. Scroll() {
      26. Column({ space: 12 }) {
      27. Row() {
      28. Text(this.text)
      29. .fontSize(20)
      30. }
      31. Divider()
      32. Text(`topAvoidHeight: ${this.topAvoidHeight}`)
      33. Text(`bottomAvoidHeight: ${this.bottomAvoidHeight}`)
      34. Text(`leftAvoidWidth: ${this.leftAvoidWidth}`)
      35. Text(`rightAvoidWidth: ${this.rightAvoidWidth}`)
      36. Text(`preferredOrientation: ${this.orientationText}`)
      37. Text(this.statusText)
      38. .fontColor('#666666')
      39. Row({ space: 8 }) {
      40. Button('Auto Rotation')
      41. .layoutWeight(1)
      42. .onClick(() => {
      43. void this.setOrientation(window.Orientation.AUTO_ROTATION, 'AUTO_ROTATION');
      44. })
      45. Button('Portrait')
      46. .layoutWeight(1)
      47. .backgroundColor('#0A7A5A')
      48. .onClick(() => {
      49. void this.setOrientation(window.Orientation.PORTRAIT, 'PORTRAIT');
      50. })
      51. Button('Landscape')
      52. .layoutWeight(1)
      53. .backgroundColor('#AD5C00')
      54. .onClick(() => {
      55. void this.setOrientation(window.Orientation.LANDSCAPE, 'LANDSCAPE');
      56. })
      57. }
      58. .width('100%')
      59. Text('Cutout test: rotate the app and observe whether leftAvoidWidth / rightAvoidWidth change on a cutout device.')
      60. .fontColor('#666666')
      61. }
      62. .width('100%')
      63. }
      64. .backgroundColor(Color.White)
      65. .padding(20)
      66. .borderRadius(15)
      67. .width('80%')
      68. .margin({
      69. left: this.getUIContext().px2vp(this.leftAvoidWidth),
      70. right: this.getUIContext().px2vp(this.rightAvoidWidth)
      71. })
      72. .layoutWeight(1)
      73. // 避让底部和挖孔区域
      74. Row() {
      75. Text('Bottom Container')
      76. .fontSize(40)
      77. .textAlign(TextAlign.Center)
      78. .width('100%')
      79. }
      80. .backgroundColor('#96dffa')
      81. .padding({
      82. top: 10,
      83. bottom: this.getUIContext().px2vp(this.bottomAvoidHeight) + 10,
      84. // 避让挖孔区域
      85. left: this.getUIContext().px2vp(this.leftAvoidWidth),
      86. right: this.getUIContext().px2vp(this.rightAvoidWidth)
      87. })
      88. }
      89. .width('100%')
      90. .height('100%')
      91. .padding({
      92. left: this.getUIContext().px2vp(this.leftAvoidWidth),
      93. right: this.getUIContext().px2vp(this.rightAvoidWidth)
      94. })
      95. .alignItems(HorizontalAlign.Center)
      96. .backgroundColor('#d5d5d5')
      97. .justifyContent(FlexAlign.SpaceBetween)
      98. }
      99. }
    • 避让使用@Env(SystemProperties.WINDOW_AVOID_AREA)获取到的避让区域的示例代码如下:

      收起
      自动换行
      深色代码主题
      复制
      1. // ...
      2. build() {
      3. Column() {
      4. Row() {
      5. Text('Top Container')
      6. .fontSize(40)
      7. .textAlign(TextAlign.Center)
      8. .width('100%')
      9. }
      10. .backgroundColor('#2786d9')
      11. .padding({
      12. top: this.avoidAreasVp.statusBar.topRect.height + 10,
      13. bottom: 10,
      14. left: this.avoidAreasVp.cutout.leftRect.width,
      15. right: this.avoidAreasVp.cutout.rightRect.width
      16. })
      17. Scroll() {
      18. Column({ space: 12 }) {
      19. Row() {
      20. Text(this.text)
      21. .fontSize(20)
      22. }
      23. Divider()
      24. Text(`topAvoidHeight: ${this.topAvoidHeight}`)
      25. Text(`bottomAvoidHeight: ${this.bottomAvoidHeight}`)
      26. Text(`leftAvoidWidth: ${this.leftAvoidWidth}`)
      27. Text(`rightAvoidWidth: ${this.rightAvoidWidth}`)
      28. Text(`preferredOrientation: ${this.orientationText}`)
      29. Text(this.statusText)
      30. .fontColor('#666666')
      31. Row({ space: 8 }) {
      32. Button('Auto Rotation')
      33. .layoutWeight(1)
      34. .onClick(() => {
      35. void this.setOrientation(window.Orientation.AUTO_ROTATION, 'AUTO_ROTATION');
      36. })
      37. Button('Portrait')
      38. .layoutWeight(1)
      39. .backgroundColor('#0A7A5A')
      40. .onClick(() => {
      41. void this.setOrientation(window.Orientation.PORTRAIT, 'PORTRAIT');
      42. })
      43. Button('Landscape')
      44. .layoutWeight(1)
      45. .backgroundColor('#AD5C00')
      46. .onClick(() => {
      47. void this.setOrientation(window.Orientation.LANDSCAPE, 'LANDSCAPE');
      48. })
      49. }
      50. .width('100%')
      51. Text('Cutout test: rotate the app and observe whether leftAvoidWidth / rightAvoidWidth change on a cutout device.')
      52. .fontColor('#666666')
      53. }
      54. .width('100%')
      55. }
      56. .backgroundColor(Color.White)
      57. .padding(20)
      58. .borderRadius(15)
      59. .width('80%')
      60. .margin({
      61. left: this.avoidAreasVp.cutout.leftRect.width,
      62. right: this.avoidAreasVp.cutout.rightRect.width
      63. })
      64. .layoutWeight(1)
      65. Row() {
      66. Text('Bottom Container')
      67. .fontSize(40)
      68. .textAlign(TextAlign.Center)
      69. .width('100%')
      70. }
      71. .backgroundColor('#96dffa')
      72. .padding({
      73. top: 10,
      74. bottom: this.avoidAreasVp.navigationIndicator.bottomRect.height + 10,
      75. left: this.avoidAreasVp.cutout.leftRect.width,
      76. right: this.avoidAreasVp.cutout.rightRect.width
      77. })
      78. }
      79. .width('100%')
      80. .height('100%')
      81. .padding({
      82. left: this.avoidAreasVp.cutout.leftRect.width,
      83. right: this.avoidAreasVp.cutout.rightRect.width
      84. })
      85. .alignItems(HorizontalAlign.Center)
      86. .backgroundColor('#d5d5d5')
      87. .justifyContent(FlexAlign.SpaceBetween)
      88. }
      89. }
  4. 根据实际的UI界面显示或相关UI元素背景颜色等,还可以按需设置状态栏的文字颜色、背景色或设置导航区域的显示或隐藏,以使UI界面效果呈现和谐。状态栏和导航区域默认是透明的,透传的是应用界面的背景色。

    此例中UI颜色比较简单,故未对状态栏文字颜色、背景色进行设置,未对导航区域进行隐藏。

展开
未适配沉浸式布局与避让区 适配沉浸式布局与避让区
在 开发与测试 开放能力API 中进行搜索
请输入您想要搜索的关键词