【纯血鸿蒙】——响应式布局如何实现?

2024-06-08 11:36

本文主要是介绍【纯血鸿蒙】——响应式布局如何实现?,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前面介绍了自适应布局,但是将窗口尺寸变化较大时,仅仅依靠自适应布局可能出现图片异常放大或页面内容稀疏留白过多等问题。此时就需要借助响应式布局能力调整页面结构。

响应式布局

响应式布局是指页面内的元素可以根据特定的特征(如窗口宽度、屏幕方向等)自动变化以适应外部容器变化的布局能力。响应式布局中最常使用的特征是窗口宽度,可以将窗口宽度划分为不同的范围(下文中称为断点)。当窗口宽度从一个断点变化到另一个断点时,改变页面布局(如将页面内容从单列排布调整为双列排布甚至三列排布等)以获得更好的显示效果。

当前系统提供了如下三种响应式布局能力,后文中我将依次展开介绍。

响应式布局能力简介
断点将窗口宽度划分为不同的范围(即断点),监听窗口尺寸变化,当断点改变时同步调整页面布局。
媒体查询媒体查询支持监听窗口宽度、横竖屏、深浅色、设备类型等多种媒体特征,当媒体特征发生改变时同步调整页面布局。
栅格布局栅格组件将其所在的区域划分为有规律的多列,通过调整不同断点下的栅格组件的参数以及其子组件占据的列数等,实现不同的布局效果。

1. 断点

1.1. 断点是什么?

断点以应用窗口宽度为切入点,将应用窗口在宽度维度上分成了几个不同的区间即不同的断点,在不同的区间下,开发者可根据需要实现不同的页面布局效果。

断点名称取值范围(**vp)**设备
xs[0, 320)手表等超小屏
sm[320, 600)手机竖屏
md[600, 840)手机横屏,折叠屏
lg[840, +∞)平板,2in1 设备

1.2. 监听断点

判断应用当前处于何种断点,进而可以调整应用的布局。常见的监听断点变化的方法如下所示:

  • 获取窗口对象并监听窗口尺寸变化(了解)

  • 通过媒体查询监听应用窗口尺寸变化(掌握

  • 借助栅格组件能力监听不同断点的变化(掌握

2. 媒体查询获取当前断点

  • 系统工具——BreakpointSystem

  • 系统工具——BreakPointType

2.1 进行工具类封装

直接给上完整代码

import mediaQuery from '@ohos.mediaquery'
​
declare interface BreakPointTypeOption<T> {xs?: Tsm?: Tmd?: Tlg?: Txl?: Txxl?: T
}
​
interface Breakpoint {name: stringsize: numbermediaQueryListener?: mediaQuery.MediaQueryListener
}
​
export const BreakpointKey: string = 'currentBreakpoint'
​
export class BreakPointType<T> {options: BreakPointTypeOption<T>
​constructor(option: BreakPointTypeOption<T>) {this.options = option}
​getValue(currentBreakPoint: string) {if (currentBreakPoint === 'xs') {return this.options.xs} else if (currentBreakPoint === 'sm') {return this.options.sm} else if (currentBreakPoint === 'md') {return this.options.md} else if (currentBreakPoint === 'lg') {return this.options.lg} else if (currentBreakPoint === 'xl') {return this.options.xl} else if (currentBreakPoint === 'xxl') {return this.options.xxl} else {return undefined}}
}
​
export class BreakpointSystem {private currentBreakpoint: string = 'md'private breakpoints: Breakpoint[] = [{ name: 'xs', size: 0 }, { name: 'sm', size: 320 },{ name: 'md', size: 600 }, { name: 'lg', size: 840 }]
​public register() {this.breakpoints.forEach((breakpoint: Breakpoint, index) => {let condition: stringif (index === this.breakpoints.length - 1) {condition = '(' + breakpoint.size + 'vp<=width' + ')'} else {condition = '(' + breakpoint.size + 'vp<=width<' + this.breakpoints[index + 1].size + 'vp)'}console.log(condition)breakpoint.mediaQueryListener = mediaQuery.matchMediaSync(condition)breakpoint.mediaQueryListener.on('change', (mediaQueryResult) => {if (mediaQueryResult.matches) {this.updateCurrentBreakpoint(breakpoint.name)}})})}
​public unregister() {this.breakpoints.forEach((breakpoint: Breakpoint) => {if (breakpoint.mediaQueryListener) {breakpoint.mediaQueryListener.off('change')}})}
​private updateCurrentBreakpoint(breakpoint: string) {if (this.currentBreakpoint !== breakpoint) {this.currentBreakpoint = breakpointAppStorage.Set<string>(BreakpointKey, this.currentBreakpoint)console.log('on current breakpoint: ' + this.currentBreakpoint)}}
}
export const breakpointSystem = new BreakpointSystem()

2.2. 通过应用级存储为所有页面提供断点

目前查询的内容只在当前页面可以使用,如果希望应用中任意位置都可以使用,咱们可以使用AppStorage 进行共享。

核心步骤:

  1. 事件中通过AppStorage.set(key,value)的方式保存当前断点值

  2. 需要使用的位置通过AppStorage来获取即可

// 添加回调函数
listenerXS.on('change', (res: mediaquery.MediaQueryResult) => {console.log('changeRes:', JSON.stringify(res))if (res.matches == true) {// this.currentBreakpoint = 'xs'AppStorage.set('currentBreakpoint', 'xs')}
})
  1. 使用断点值

// 组件中引入 AppStorage
@StorageProp('currentBreakpoint') currentBreakpoint: CurrentBreakpoint = 'xs'
​
// 在需要的位置使用 AppStorage 中保存的断点值
Text(this.currentBreakpoint)

2.3. 使用断点

核心用法:

  1. 导入 BreakpointSystem

  2. 实例化BreakpointSystem

  3. aboutToAppear中注册监听事件 aboutToDisappear中移除监听事件

  4. 通过 AppStorage,结合 获取断点值即可

// 1. 导入
import { BreakPointType, BreakpointSystem, BreakpointKey } from '../../common/breakpointsystem'
​
​
@Entry
@Component
struct Example {
​// 2. 实例化breakpointSystem: BreakpointSystem = new BreakpointSystem()// 4. 通过 AppStorage 获取断点值@StorageProp(BreakpointKey)currentBreakpoint: string = 'sm'
​// 3. 注册及移除监听事件aboutToAppear(): void {this.breakpointSystem.register()}
​aboutToDisappear(): void {this.breakpointSystem.unregister()}
​build() {// 略}
}

2.4. 案例-电影列表

使用刚刚学习的媒体查询工具,结合断点来完成一个响应式案例效果,达到跨任意终端皆能实现响应式布局的效果。

image.png

完整代码:

import { BreakPointType, BreakpointSystem, BreakpointKey } from '../../common/breakpointsystem'
​
interface MovieItem {title: stringimg: ResourceStr
}
​
@Entry
@Component
struct Demo09_demo {items: MovieItem[] = [{ title: '电影标题1', img: $r('app.media.ic_video_grid_1') },{ title: '电影标题2', img: $r('app.media.ic_video_grid_2') },{ title: '电影标题3', img: $r('app.media.ic_video_grid_3') },{ title: '电影标题4', img: $r('app.media.ic_video_grid_4') },{ title: '电影标题5', img: $r('app.media.ic_video_grid_5') },{ title: '电影标题6', img: $r('app.media.ic_video_grid_6') },{ title: '电影标题7', img: $r('app.media.ic_video_grid_7') },{ title: '电影标题8', img: $r('app.media.ic_video_grid_8') },{ title: '电影标题9', img: $r('app.media.ic_video_grid_9') },{ title: '电影标题10', img: $r('app.media.ic_video_grid_10') },]breakpointSystem: BreakpointSystem = new BreakpointSystem()@StorageProp(BreakpointKey)currentBreakpoint: string = 'sm'
​aboutToAppear(): void {this.breakpointSystem.register()}
​aboutToDisappear(): void {this.breakpointSystem.unregister()}
​build() {Grid() {ForEach(this.items, (item: MovieItem) => {GridItem() {Column({ space: 10 }) {Image(item.img).borderRadius(10)Text(item.title).width('100%').fontSize(20).fontWeight(600)
​}}})}.columnsTemplate(new BreakPointType({xs: '1fr 1fr',sm: '1fr 1fr ',md: '1fr 1fr 1fr ',lg: '1fr 1fr 1fr 1fr '}).getValue(this.currentBreakpoint)).rowsGap(10).columnsGap(10).padding(10)}
}

效果:

3. 栅格布局 Grid

栅格组件的本质是:将组件划分为有规律的多列,通过调整【不同断点】下的【栅格组件的列数】,及【子组件所占列数】实现不同布局

比如:

img

参考栅格列数设置:

img

核心用法

优先级从上往下:

  1. GridRow的 columns 属性、GridCol 的 span 属性(掌握)

  2. GridRow 的 gutter属性、GridCol 的 offset 属性(掌握)

  3. GridRow breakpoints属性 和 的 onBreakpointChange 事件(了解)

@Entry
@Component
struct Demo11_login {build() {Stack() {// 辅助用的栅格(顶层粉色区域)GridRow({ gutter: 10, columns: { sm: 4, md: 8, lg: 12 } }) {ForEach(Array.from({ length: 12 }), () => {GridCol().width('100%').height('100%').backgroundColor('#baffa2b4')})}.zIndex(2).height('100%')
​//  内容区域GridRow({// TODO 分别设置不同断点的 列数columns: {sm: 4,md: 8,lg: 12}}) {// 列GridCol({// TODO 分别设置不同断点的 所占列数span: {sm: 4,md: 6,lg: 8},// TODO 分别设置不同断点的 偏移offset: {md: 1,lg: 2}
​}) {Column() {// logo+文字LogoCom()
​// 输入框 + 底部提示文本InputCom()
​// 登录+注册账号按钮ButtonCom()
​}}}.width('100%').height('100%').backgroundColor('#ebf0f2')}}
}
​
@Component
struct LogoCom {build() {Column({ space: 5 }) {Image($r('app.media.ic_logo')).width(80)Text('登录界面').fontSize(23).fontWeight(900)Text('登录账号以使用更多服务').fontColor(Color.Gray)}.margin({ top: 100 })}
}
​
@Component
struct InputCom {build() {Column() {Column() {TextInput({ placeholder: '账号' }).backgroundColor(Color.Transparent)Divider().color(Color.Gray)TextInput({ placeholder: '密码' }).type(InputType.Password).backgroundColor(Color.Transparent)
​}.backgroundColor(Color.White).borderRadius(20).padding({ top: 10, bottom: 10 })
​Row() {Text('短信验证码登录').fontColor('#006af7').fontSize(14)Text('忘记密码').fontColor('#006af7').fontSize(14)}.width('100%').justifyContent(FlexAlign.SpaceBetween).margin({ top: 10 })
​}.padding(5).margin({ top: 80 })
​}
}
​
@Component
struct ButtonCom {build() {Column({ space: 10 }) {Button('登录').width('90%')Text('注册账号').fontColor('#006af7').fontSize(16)}.margin({ top: 60 })}
}

下面我给栅格布局加了颜色方便展示效果:

这篇关于【纯血鸿蒙】——响应式布局如何实现?的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1042068

相关文章

Flutter实现文字镂空效果的详细步骤

《Flutter实现文字镂空效果的详细步骤》:本文主要介绍如何使用Flutter实现文字镂空效果,包括创建基础应用结构、实现自定义绘制器、构建UI界面以及实现颜色选择按钮等步骤,并详细解析了混合模... 目录引言实现原理开始实现步骤1:创建基础应用结构步骤2:创建主屏幕步骤3:实现自定义绘制器步骤4:构建U

SpringBoot中四种AOP实战应用场景及代码实现

《SpringBoot中四种AOP实战应用场景及代码实现》面向切面编程(AOP)是Spring框架的核心功能之一,它通过预编译和运行期动态代理实现程序功能的统一维护,在SpringBoot应用中,AO... 目录引言场景一:日志记录与性能监控业务需求实现方案使用示例扩展:MDC实现请求跟踪场景二:权限控制与

Android实现定时任务的几种方式汇总(附源码)

《Android实现定时任务的几种方式汇总(附源码)》在Android应用中,定时任务(ScheduledTask)的需求几乎无处不在:从定时刷新数据、定时备份、定时推送通知,到夜间静默下载、循环执行... 目录一、项目介绍1. 背景与意义二、相关基础知识与系统约束三、方案一:Handler.postDel

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义