鸿蒙多功能工具箱开发实战(三十二)-多设备适配与响应式布局 鸿蒙多功能工具箱开发实战(三十二)-多设备适配与响应式布局前言HarmonyOS支持多种设备形态多设备适配是开发的重要环节。本文将讲解响应式布局和多设备适配策略。一、设备类型1.1 设备分类类型宽度范围典型设备小屏 600dp手机竖屏中屏600-840dp手机横屏、小平板大屏 840dp平板、折叠屏1.2 设备信息获取importdisplayfromohos.displayimportdeviceInfofromohos.deviceInfoexportclassDeviceUtil{/** * 获取设备类型 */staticgetDeviceType():phone|tablet|tv|wearable{consttypedeviceInfo.deviceTypeswitch(type){casephone:returnphonecasetablet:returntabletcasetv:returntvcasewearable:returnwearabledefault:returnphone}}/** * 获取屏幕宽度 */staticgetScreenWidth():number{constdisplayInfodisplay.getDefaultDisplaySync()returndisplayInfo.width}/** * 获取屏幕高度 */staticgetScreenHeight():number{constdisplayInfodisplay.getDefaultDisplaySync()returndisplayInfo.height}/** * 是否横屏 */staticisLandscape():boolean{returnthis.getScreenWidth()this.getScreenHeight()}/** * 是否大屏设备 */staticisLargeScreen():boolean{constwidthpx2vp(this.getScreenWidth())returnwidth600}}1.3 网络请求流程图服务器HTTP模块HttpUtil应用层服务器HTTP模块HttpUtil应用层发起请求构建请求参数调用request()发送HTTP请求返回响应数据响应结果解析响应返回数据二、响应式布局2.1 媒体查询importmediaQueryfromohos.mediaqueryexportclassMediaQueryUtil{privatestaticlistener:mediaQuery.MediaQueryListener/** * 监听屏幕变化 */staticlistenScreenChange(callback:(isLarge:boolean)void):void{constconditionmediaQuery.matchConditionSync(screen and (min-width: 600vp))this.listenermediaQuery.matchCondition(condition,(result:mediaQuery.MediaQueryResult){callback(result.matches)})}/** * 取消监听 */staticunlisten():void{if(this.listener){mediaQuery.unmatchCondition(this.listener)}}}2.2 响应式组件Componentexportstruct ResponsiveLayout{StateisLargeScreen:booleanfalseaboutToAppear(){this.isLargeScreenDeviceUtil.isLargeScreen()MediaQueryUtil.listenScreenChange((isLarge){this.isLargeScreenisLarge})}aboutToDisappear(){MediaQueryUtil.unlisten()}BuilderParamsmallContent:()voidBuilderParamlargeContent:()voidbuild(){if(this.isLargeScreen){this.largeContent()}else{this.smallContent()}}}2.3 使用示例EntryComponentstruct ResponsivePage{build(){ResponsiveLayout({smallContent:(){// 小屏布局单列Column(){this.ContentArea()}},largeContent:(){// 大屏布局双列Row(){this.SideBar()this.ContentArea()}}})}BuilderSideBar(){Column(){Text(侧边栏)}.width(240).backgroundColor(#F5F5F5)}BuilderContentArea(){Column(){Text(内容区域)}.layoutWeight(1)}}三、栅格布局3.1 栅格系统Componentexportstruct GridContainer{Propcolumns:number12Propgutter:number16BuilderParamcontent:()voidbuild(){Row(){this.content()}.width(100%)}}Componentexportstruct GridColumn{Propspan:number12// 占用列数Propoffset:number0// 偏移列数BuilderParamcontent:()voidbuild(){Column(){this.content()}.width(${(this.span/12)*100}%).margin({left:${(this.offset/12)*100}%})}}3.2 响应式栅格Componentexportstruct ResponsiveGrid{Statecolumns:number12StateisLargeScreen:booleanfalseaboutToAppear(){this.updateColumns()MediaQueryUtil.listenScreenChange((isLarge){this.isLargeScreenisLargethis.updateColumns()})}privateupdateColumns(){this.columnsthis.isLargeScreen?12:4}build(){Grid(){// 栅格内容}.columnsTemplate(repeat(${this.columns}, 1fr))}}四、多设备资源4.1 资源目录结构resources/ ├── base/ # 默认资源 │ ├── element/ │ │ └── string.json │ └── media/ │ └── icon.png ├── phone/ # 手机资源 │ └── media/ │ └── icon.png # 手机尺寸图标 └── tablet/ # 平板资源 └── media/ └── icon.png # 平板尺寸图标4.2 设备特定配置exportclassResourceUtil{/** * 获取设备特定资源 */staticgetDeviceResource(baseName:string):Resource{constdeviceTypeDeviceUtil.getDeviceType()// 根据设备类型返回不同资源switch(deviceType){casetablet:return$r(app.media.${baseName}_tablet)default:return$r(app.media.${baseName})}}/** * 获取尺寸相关值 */staticgetDimensionValue(config:{small:numbermedium:numberlarge:number}):number{constwidthpx2vp(DeviceUtil.getScreenWidth())if(width600)returnconfig.smallif(width840)returnconfig.mediumreturnconfig.large}}五、适配最佳实践5.1 弹性尺寸EntryComponentstruct AdaptivePage{build(){Column(){// 使用百分比宽度Row(){Column().width(30%).backgroundColor(#F5F5F5)Column().width(70%).backgroundColor(#FFFFFF)}.width(100%)// 使用layoutWeightRow(){Column().layoutWeight(1).backgroundColor(#F5F5F5)Column().layoutWeight(2).backgroundColor(#FFFFFF)}.width(100%)}}}5.2 字体适配exportclassFontSizeUtil{/** * 获取适配字体大小 */staticgetFontSize(baseSize:number):number{constdeviceTypeDeviceUtil.getDeviceType()switch(deviceType){casetablet:returnbaseSize*1.25casetv:returnbaseSize*1.5default:returnbaseSize}}}// 使用Text(标题).fontSize(FontSizeUtil.getFontSize(18))六、高级适配技巧6.1 设备适配流程图手机平板折叠屏获取设备信息判断设备类型设备类型应用手机布局应用平板布局应用折叠屏布局渲染UI6.2 自适应组件Componentstruct AdaptiveLayout{StatedeviceType:stringphoneaboutToAppear(){this.deviceTypeDeviceUtil.getDeviceType()}build(){if(this.deviceTypetablet){this.TabletLayout()}else{this.PhoneLayout()}}BuilderTabletLayout(){Row(){this.SidePanel()this.MainContent()}}BuilderPhoneLayout(){Column(){this.MainContent()}}}6.3 资源限定符resources/ base/ # 默认资源 phone/ # 手机资源 tablet/ # 平板资源 tv/ # TV资源 wearable/ # 可穿戴设备资源七、小结本文详细讲解了多设备适配✅ 设备类型判断✅ 媒体查询✅ 响应式布局✅ 栅格系统✅ 多设备资源✅ 自适应组件✅ 资源限定符系列文章导航下期预告鸿蒙多功能工具箱开发实战(三十三)-折叠屏适配