先明確需求:應(yīng)用全局是豎屏的,個別頁面要支持橫屏,且這個橫屏是受控制中心的手機方向鎖定限制。
因為是要鎖定應(yīng)用豎屏,所以module.json5中要設(shè)置:
"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
}
然后在需要要支持橫屏的頁面里實現(xiàn)如下方法:
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)中幾個枚舉值的區(qū)別:

image.png
因此我們這里選擇了AUTO_ROTATION_RESTRICTED。如果設(shè)置AUTO_ROTATION,那么就會忽略手機控制中心里的手機方向鎖定鍵,頁面始終與手機物理方向保持一致。