通过on('windowSizeChange')监听设备的横竖屏变化,并动态的更改页面布局。
import { window } from '@kit.ArkUI';
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct LandscapeDemo {
@State isLandscape: boolean = false;
getWindow(): window.Window {
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let windowStage = context.windowStage;
let windowClass = windowStage.getMainWindowSync();
return windowClass;
}
onPageShow(): void {
let windowClass: window.Window = this.getWindow();
let properties = windowClass.getWindowProperties();
let rect = properties.windowRect;
this.isLandscape = rect.width > rect.height;
}
aboutToAppear() {
let windowClass: window.Window = this.getWindow();
// 监听窗口尺寸的变化
windowClass.on('windowSizeChange', (data) => {
this.isLandscape = data.width > data.height;
});
}
build() {
Column() {
if (this.isLandscape === true) {
// 横屏的布局
Text('当前是横屏状态');
} else {
// 竖屏的布局
Text('当前是竖屏状态');
}
}
.width('100%')
.height('100%');
}
}