鸿蒙实现应用锁定竖屏,个别页面支持横屏

先明确需求:应用全局是竖屏的,个别页面要支持横屏,且这个横屏是受控制中心的手机方向锁定限制。

因为是要锁定应用竖屏,所以module.json5中要设置:

"orientation": "portrait",  // 固定屏幕方向

由于要在支持横屏的页面中用到mainwindow

let windowStage: window.WindowStage = AppStorage.get('windowStage') as window.WindowStage;

所以需要在你的 EntryAbility.ets文件中,先保存一个全局的windowStage:

  onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    AppStorage.setOrCreate("windowStage",windowStage) //保存windowStage
}

然后在需要要支持横屏的页面里实现如下方法:

aboutToAppear(): void {
  this.changeScreenOrientation(window.Orientation.AUTO_ROTATION_RESTRICTED);
}

aboutToDisappear(): void {
    this.changeScreenOrientation(window.Orientation.PORTRAIT);
}

changeScreenOrientation(orientation: window.Orientation) {
    let windowStage: window.WindowStage = AppStorage.get('windowStage') as window.WindowStage;
    let windowClass: window.Window;
    windowStage.getMainWindow((err, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      try {
        windowClass.setPreferredOrientation(orientation, (err) => {
        const errCode: number = err.code;
          if (errCode) {
            console.error(`Failed to set window orientation. Cause code: ${err.code}, message: ${err.message}`);
            return;
          }
          console.info('Succeeded in setting window orientation.');
        });
      } catch (exception) {
        console.error(`Failed to set window orientation. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
}

解释一下Orientation(https://developer.huawei.com/consumer/cn/doc/harmonyos-references/arkts-apis-window-e#orientation9)中几个枚举值的区别:

image.png

因此我们这里选择了AUTO_ROTATION_RESTRICTED。如果设置AUTO_ROTATION,那么就会忽略手机控制中心里的手机方向锁定键,页面始终与手机物理方向保持一致。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容