监听windowSizeChange事件,动态调整布局并设置小窗口布局。适配分屏的应用保证页面布局能够完整显示,避免出现截断、挤压、堆叠等现象。
export default class MainAbility extends UIAbility {
private windowObj?: window.Window
private curBp: string = ''
private updateBreakpoint(windowWidth: number) :void{
// 拿到当前窗口对象获取当前所在displayId
let displayId = this.windowObj?.getWindowProperties().displayId
try {
let windowWidthVp = windowWidth / display.getDisplayByIdSync(displayId).densityPixels
let newBp: string = ''
if (windowWidthVp < 320) {
newBp = 'xs'
} else if (windowWidthVp < 600) {
newBp = 'sm'
} else if (windowWidthVp < 840) {
newBp = 'md'
} else {
newBp = 'lg'
}
if (this.curBp !== newBp) {
this.curBp = newBp
AppStorage.setOrCreate('currentBreakpoint', this.curBp);
}
} catch(err) {
console.log("getDisplayByIdSync failed err"+err.code);
}
}
} onWindowStageCreate(windowStage: window.WindowStage) :void{
windowStage.getMainWindow().then((windowObj) => {
this.windowObj = windowObj
// 获取应用启动时的窗口尺寸
this.updateBreakpoint(windowObj.getWindowProperties().windowRect.width);
// 注册回调函数,监听窗口尺寸变化
windowObj.on('windowSizeChange', (windowSize)=>{
this.updateBreakpoint(windowSize.width)
})
});
// ...
} // 以设置图片的高度为例,在小窗口布局中高度为24vp,手机全屏时高度为48vp。使用横纵向断点判断,设置具体的属性值。
Image($r('app.media.arrow_right'))
.height(this.currentWidthBreakpoint === 'sm' && (this.currentHeightBreakpoint === 'sm' ||
this.currentHeightBreakpoint === 'md') ? 24 : 48)
.aspectRatio(1)