HarmonyOS 使用Navigation时候如何实现横竖屏切换?

首页使用了Navigation,是竖屏,二级页面使用NavDestination,是横屏,如何完成横竖屏切换

阅读 566
1 个回答

可以参考此文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-window-V5\#setpreferredorientation9

//EntryAbility.ets里AppStorage.setOrCreate('windowStage',windowStage)
onWindowStageCreate(windowStage: window.WindowStage): void {
  windowStage.loadContent('pages/Index', (err, data) => {
  if (err.code) {
  hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
  return;
}
AppStorage.setOrCreate('windowStage',windowStage)
});
}

//NavDestination二级页面调用设置横竖屏函数
let windowStage: window.WindowStage = AppStorage.get("windowStage") as window.WindowStage
let orientation = window.Orientation.LANDSCAPE;
onWindowStageCreate(windowStage, orientation)


// 设置横竖屏函数
export async function onWindowStageCreate(windowStage: window.WindowStage, orientation: number): Promise<void> {
  console.info('onWindowStageCreate');
  const s = systemDateTime.getTime()
  let windowClass: window.Window | undefined = undefined;
  windowStage.getMainWindow((err: BusinessError, 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: BusinessError) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to set window orientation. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        const e = systemDateTime.getTime()
        console.info('Succeeded in setting window orientation.');
      });
    } catch (exception) {
      console.error(`Failed to set window orientation. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  });
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进