在HarmonyOS NEXT开发中怎么在Page中获取窗口的宽高?不是设备的宽高,是要获取二分屏窗口大小,三分屏窗口大小,悬浮窗口大小
在HarmonyOS NEXT开发中怎么在Page中获取窗口的宽高?不是设备的宽高,是要获取二分屏窗口大小,三分屏窗口大小,悬浮窗口大小
在HarmonyOS NEXT中获取动态窗口尺寸(如二分屏、三分屏、悬浮窗),可通过以下两种核心方案实现:
方案一:窗口管理器监听(推荐)
import window from '@ohos.window';
@Entry
@Component
struct Index {
@State windowWidth: number = 0
@State windowHeight: number = 0
aboutToAppear() {
window.getLastWindow(this.context).then((win) => {
// 初始获取
win.getWindowProperties().then(props => {
this.windowWidth = props.windowRect.width;
this.windowHeight = props.windowRect.height;
});
// 注册窗口变化监听
win.on('windowSizeChange', (rect) => {
this.windowWidth = rect.width;
this.windowHeight = rect.height;
});
});
}
}
方案二:ArkUI布局回调
@Component
struct WindowSizeDisplay {
@State winWidth: number = 0
@State winHeight: number = 0
build() {
Column() {
Text(`窗口尺寸:${this.winWidth}x${this.winHeight}`)
}
.onAreaChange((oldVal, newVal) => {
this.winWidth = newVal.width;
this.winHeight = newVal.height;
})
}
}
关键特性说明:
扩展应用场景:
// 自适应布局判断
if (this.windowWidth < 600) { // 600vp为折叠屏展开阈值
// 手机布局
} else {
// 平板/分屏布局
}
// 横竖屏检测
const isLandscape = this.windowWidth > this.windowHeight;
注意事项:
需要在module.json5中添加权限:
"requestPermissions": [
"ohos.permission.GET_WINDOW_INFO"
]
试试窗口的getWindowproperties().windowRect()方法,然后就可以获取其width和height属性了。