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

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

响应式布局

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

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

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

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.mzph.cn/diannao/24513.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

docker部署使用本地文件的fastapi项目

项目背景&#xff1a;项目使用python开发&#xff0c;需要使用ubutun系统部署后端api接口&#xff0c;对外使用8901端口。 1:项目结构&#xff1a; 2&#xff1a;项目需要使用的pyhton版本为3.9&#xff0c;dockerfile内容如下&#xff1a; # FROM python:3.9# WORKDIR /co…

自制植物大战僵尸:HTML5与JavaScript实现的简单游戏

引言 在本文中&#xff0c;我们将一起探索如何使用HTML5和JavaScript来创建一个简单的植物大战僵尸游戏。这不仅是一项有趣的编程挑战&#xff0c;也是学习游戏开发基础的绝佳机会。 什么是植物大战僵尸&#xff1f; 植物大战僵尸是一款流行的策略塔防游戏&#xff0c;玩家需…

如何提高网站排名?

提高网站排名是一个复杂的过程&#xff0c;涉及到多个方面的优化&#xff0c;包括但不限于内容质量、网站结构、用户体验、外部链接建设等&#xff0c;GSR这个系统&#xff0c;它是一种快速提升关键词排名的方案&#xff0c;不过它有个前提&#xff0c;就是你的站点在目标关键词…

超详解——深入详解Python基础语法——小白篇

目录 1 .语句和变量 变量赋值示例&#xff1a; 打印变量的值&#xff1a; 2. 语句折行 反斜杠折行示例&#xff1a; 使用括号自动折行&#xff1a; 3. 缩进规范 缩进示例&#xff1a; 4. 多重赋值&#xff08;链式赋值&#xff09; 多重赋值的应用&#xff1a; 5 .多…

FonesGo Location Changer 用Mac修改iPhone定位的工具

搜索Mac软件之家下载FonesGo Location Changer 用Mac修改iPhone定位的工具 FonesGo Location Changer 7.0.0 可以自定义修改iPhone和Android手机的GPS定位。FonesGo Location Changer 是玩 Pokemon Go 时的最佳搭档。您可以以自定义速度模拟 GPS 运动&#xff0c;例如步行、骑…

【设计模式】JAVA Design Patterns——State(状态模式)

&#x1f50d;目的 允许对象在内部状态改变时改变它的行为。对象看起来好像修改了它的类。 &#x1f50d;解释 真实世界例子 当在长毛象的自然栖息地观察长毛象时&#xff0c;似乎它会根据情况来改变自己的行为。它开始可能很平静但是随着时间推移当它检测到威胁时它会对周围的…

element-plus 的icon 图标的使用

element-plus的icon 已经独立出来了&#xff0c;需要单独安装 1. npm安装 icon包 npm install element-plus/icons-vue2.注册到全局组件中 同时注册到全局组件中&#xff0c;或者按需单独引入&#xff0c;这里只介绍全局引入。 import { createApp } from vue import { cre…

Python易错点总结

目录 多分支选择结构 嵌套选择 用match模式识别 match与if的对比 案例&#xff1a;闰年判断 三角形的判断 用whlie循环 高斯求和 死循环 用for循环 ​编辑continue​编辑 whlie与else结合 pass 序列 列表&#xff08;有序&#xff09; 元组&#xff08;有序&…

LeetCode热题100—链表(二)

19.删除链表的倒数第N个节点 题目 给你一个链表&#xff0c;删除链表的倒数第 n 个结点&#xff0c;并且返回链表的头结点。 示例 1&#xff1a; 输入&#xff1a;head [1,2,3,4,5], n 2 输出&#xff1a;[1,2,3,5] 示例 2&#xff1a; 输入&#xff1a;head [1], n 1 …

Docker中搭建likeadmin

一、使用Docker中的docker-compose搭建likeadmin 1.去网址&#xff1a;https://gitee.com/likeadmin/likeadmin_php中下载likeadmin 注册一个giee账号后 点那个克隆下载 按照序号在终端复制粘贴进去。 接着&#xff0c;输入ls 可以发现有一个这个&#xff1a; 里面有一个like…

摄影店展示服务预约小程序的作用是什么

摄影店包含婚照、毕业照、写真、儿童照、工作照等多个服务项目&#xff0c;虽然如今人们手机打开便可随时拍照摄影&#xff0c;但在专业程度和场景应用方面&#xff0c;却是需要前往专业门店服务获取。 除了进店&#xff0c;也有外部预约及活动、同行合作等场景&#xff0c;重…

Ezsql(buuctf加固题)

开启环境 SSH连接 第一个为页面地址WEB服务 or 11# 利用万能密码登录 密码可以随便输入或者不输入 这里就可以判断这个题目是让我们加固这个登录页面 防止sql注入 查看index.php 添加以下代码 $username addslashes($username); $password addslashes($password);…

2024年京东618红包领取跨店满300减50第二波活动时间什么时候开始到几号结束?

2024年京东618活动时间 整个618红包满减活动时间是从&#xff1a;2024年5月28日12:00开始一直持续到6月20日23:59 第一波红包领取活动时间是从&#xff1a;2024年5月28日12:00开始到6月6日23:59结束 第二波红包领取活动时间是从&#xff1a;2024年6月7日00:00开始到6月18日2…

【HarmonyOS】放大缩小手势实现

【HarmonyOS】放大缩小手势实现 一、鸿蒙中手势的类型&#xff1a; 对于放大缩小手势&#xff0c;在应用开发中使用较为常见&#xff0c;例如预览图片时&#xff0c;扫码时等。 在鸿蒙中对于常见的手势进行的封装&#xff0c;可以通过简单的API进行监听调用&#xff0c;以下是…

k8s测试题

k8s集群k8s集群node01192.168.246.11k8s集群node02192.168.246.12k8s集群master 192.168.246.10 k8s集群nginxkeepalive负载均衡nginxkeepalive01&#xff08;master&#xff09;192.168.246.13负载均衡nginxkeepalive02&#xff08;backup&#xff09;192.168.246.14VIP 192…

【因果推断python】24_倾向得分2

目录 倾向加权 倾向得分估计 倾向加权 好的&#xff0c;我们得到了倾向得分。怎么办&#xff1f;就像我说过的&#xff0c;我们需要做的就是以此为条件。例如&#xff0c;我们可以运行一个线性回归&#xff0c;它仅以倾向得分为条件&#xff0c;而不是所有的 X。现在&#xff…

【postgresql初级使用】视图上的触发器instead of,替代计划的rewrite,实现不一样的审计日志

instead of 触发器 ​专栏内容&#xff1a; postgresql使用入门基础手写数据库toadb并发编程 个人主页&#xff1a;我的主页 管理社区&#xff1a;开源数据库 座右铭&#xff1a;天行健&#xff0c;君子以自强不息&#xff1b;地势坤&#xff0c;君子以厚德载物. 文章目录 inst…

Python私教张大鹏 Vue3整合AntDesignVue之Layout布局

案例&#xff1a;栅格布局 核心代码&#xff1a; <template><a-row><a-col :span"24">col</a-col></a-row><a-row><a-col :span"12">col-12</a-col><a-col :span"12">col-12</a-col…

国际货币基金组织警告:网络攻击影响全球金融稳定

近日&#xff0c;在一份关于金融稳定的报告中&#xff0c;国际货币基金组织&#xff08;IMF&#xff09;用了一章&#xff08;共三章&#xff09;的篇幅描述了网络攻击对金融环境的影响&#xff0c;并警告称&#xff0c;全球金融稳定正受到日益频繁和复杂的网络攻击的威胁。同时…

面试题react03

React事件机制&#xff1a; React的事件机制可以分为两个部分&#xff1a;事件的触发和事件的处理。事件的触发&#xff1a;在React中&#xff0c;事件可以通过用户与组件进行交互而触发&#xff0c;如点击、鼠标移动、键盘输入等。当用户与组件进行交互时&#xff0c;浏览器会…