【HarmonyOS】API9沉浸式状态栏

发布时间 2023-08-15 10:28:05作者: Mayism123
 对于沉浸式状态栏,在之前API8 FA模型开发中可以通过在config.json配置主题的方式实现应用的沉浸式体验,在最新的API9 Stage模型中系统提供了沉浸式窗口的示例(管理应用窗口(Stage模型)-窗口管理-开发-HarmonyOS应用开发)。通过调用setWindowSystemBarEnable接口,设置导航栏、状态栏不显示,从而达到沉浸式效果。

但是这种方式仅仅式隐藏了状态栏和导航栏,程序运行后状态栏和导航栏会显示为黑色,无法实现状态栏与App颜色一致,如下图:

cke_3478.png

 如果要显示完全的沉浸式效果,可以将当前应用窗口设置为全屏样式实现。关键代码是:

windowClass.setWindowLayoutFullScreen(true)

通过设置为全屏就可以实现状态栏和导航栏全覆盖的效果:

cke_30737.png​​

最后onWindowStageCreate关键代码如下,以供大家参考:

onWindowStageCreate(windowStage) {

  // 1.获取应用主窗口。
  let windowClass = null;
  windowStage.getMainWindow((err, data) => {

    if (err.code) {
      console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err));
      return;
    }

    windowClass = data;
    console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data));


    // 2.实现沉浸式效果:设置导航栏、状态栏不显示。
    let names = [];
    windowClass.setWindowSystemBarEnable(names, (err) => {
      if (err.code) {
        console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err));
        return;
      }
      console.info('Succeeded in setting the system bar to be visible.');
    });

    windowClass.setWindowLayoutFullScreen(true)
  })


  // 3.为沉浸式窗口加载对应的目标页面。
  windowStage.loadContent("pages/Index", (err) => {
    if (err.code) {
      console.error('Failed to load the content. Cause:' + JSON.stringify(err));
      return;
    }
    console.info('Succeeded in loading the content.');
  });
}