当前位置:   article > 正文

【纯血鸿蒙】——响应式布局如何实现?_响应式布局中将窗口宽度划分为两种类型

响应式布局中将窗口宽度划分为两种类型

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

响应式布局

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

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

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

1. 断点

1.1. 断点是什么?

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

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

1.2. 监听断点

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

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

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

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

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

  • 系统工具——BreakpointSystem

  • 系统工具——BreakPointType

2.1 进行工具类封装

直接给上完整代码

  1. import mediaQuery from '@ohos.mediaquery'
  2. declare interface BreakPointTypeOption<T> {
  3.  xs?: T
  4.  sm?: T
  5.  md?: T
  6.  lg?: T
  7.  xl?: T
  8.  xxl?: T
  9. }
  10. interface Breakpoint {
  11.  name: string
  12.  size: number
  13.  mediaQueryListener?: mediaQuery.MediaQueryListener
  14. }
  15. export const BreakpointKey: string = 'currentBreakpoint'
  16. export class BreakPointType<T> {
  17.  options: BreakPointTypeOption<T>
  18.  constructor(option: BreakPointTypeOption<T>) {
  19.    this.options = option
  20. }
  21.  getValue(currentBreakPoint: string) {
  22.    if (currentBreakPoint === 'xs') {
  23.      return this.options.xs
  24.   } else if (currentBreakPoint === 'sm') {
  25.      return this.options.sm
  26.   } else if (currentBreakPoint === 'md') {
  27.      return this.options.md
  28.   } else if (currentBreakPoint === 'lg') {
  29.      return this.options.lg
  30.   } else if (currentBreakPoint === 'xl') {
  31.      return this.options.xl
  32.   } else if (currentBreakPoint === 'xxl') {
  33.      return this.options.xxl
  34.   } else {
  35.      return undefined
  36.   }
  37. }
  38. }
  39. export class BreakpointSystem {
  40.  private currentBreakpoint: string = 'md'
  41.  private breakpoints: Breakpoint[] = [
  42.   { name: 'xs', size: 0 }, { name: 'sm', size: 320 },
  43.   { name: 'md', size: 600 }, { name: 'lg', size: 840 }
  44. ]
  45.  public register() {
  46.    this.breakpoints.forEach((breakpoint: Breakpoint, index) => {
  47.      let condition: string
  48.      if (index === this.breakpoints.length - 1) {
  49.        condition = '(' + breakpoint.size + 'vp<=width' + ')'
  50.     } else {
  51.        condition = '(' + breakpoint.size + 'vp<=width<' + this.breakpoints[index + 1].size + 'vp)'
  52.     }
  53.      console.log(condition)
  54.      breakpoint.mediaQueryListener = mediaQuery.matchMediaSync(condition)
  55.      breakpoint.mediaQueryListener.on('change', (mediaQueryResult) => {
  56.        if (mediaQueryResult.matches) {
  57.          this.updateCurrentBreakpoint(breakpoint.name)
  58.       }
  59.     })
  60.   })
  61. }
  62.  public unregister() {
  63.    this.breakpoints.forEach((breakpoint: Breakpoint) => {
  64.      if (breakpoint.mediaQueryListener) {
  65.        breakpoint.mediaQueryListener.off('change')
  66.     }
  67.   })
  68. }
  69.  private updateCurrentBreakpoint(breakpoint: string) {
  70.    if (this.currentBreakpoint !== breakpoint) {
  71.      this.currentBreakpoint = breakpoint
  72.      AppStorage.Set<string>(BreakpointKey, this.currentBreakpoint)
  73.      console.log('on current breakpoint: ' + this.currentBreakpoint)
  74.   }
  75. }
  76. }
  77. export const breakpointSystem = new BreakpointSystem()

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

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

核心步骤:

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

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

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

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

2.3. 使用断点

核心用法:

  1. 导入 BreakpointSystem

  2. 实例化BreakpointSystem

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

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

  1. // 1. 导入
  2. import { BreakPointType, BreakpointSystem, BreakpointKey } from '../../common/breakpointsystem'
  3. @Entry
  4. @Component
  5. struct Example {
  6. // 2. 实例化
  7. breakpointSystem: BreakpointSystem = new BreakpointSystem()
  8. // 4. 通过 AppStorage 获取断点值
  9. @StorageProp(BreakpointKey)
  10. currentBreakpoint: string = 'sm'
  11. // 3. 注册及移除监听事件
  12. aboutToAppear(): void {
  13.   this.breakpointSystem.register()
  14. }
  15. aboutToDisappear(): void {
  16.   this.breakpointSystem.unregister()
  17. }
  18. build() {
  19.   // 略
  20. }
  21. }

2.4. 案例-电影列表

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

image.png

完整代码:

  1. import { BreakPointType, BreakpointSystem, BreakpointKey } from '../../common/breakpointsystem'
  2. interface MovieItem {
  3.  title: string
  4.  img: ResourceStr
  5. }
  6. @Entry
  7. @Component
  8. struct Demo09_demo {
  9.  items: MovieItem[] = [
  10.   { title: '电影标题1', img: $r('app.media.ic_video_grid_1') },
  11.   { title: '电影标题2', img: $r('app.media.ic_video_grid_2') },
  12.   { title: '电影标题3', img: $r('app.media.ic_video_grid_3') },
  13.   { title: '电影标题4', img: $r('app.media.ic_video_grid_4') },
  14.   { title: '电影标题5', img: $r('app.media.ic_video_grid_5') },
  15.   { title: '电影标题6', img: $r('app.media.ic_video_grid_6') },
  16.   { title: '电影标题7', img: $r('app.media.ic_video_grid_7') },
  17.   { title: '电影标题8', img: $r('app.media.ic_video_grid_8') },
  18.   { title: '电影标题9', img: $r('app.media.ic_video_grid_9') },
  19.   { title: '电影标题10', img: $r('app.media.ic_video_grid_10') },
  20. ]
  21.  breakpointSystem: BreakpointSystem = new BreakpointSystem()
  22.  @StorageProp(BreakpointKey)
  23.  currentBreakpoint: string = 'sm'
  24.  aboutToAppear(): void {
  25.    this.breakpointSystem.register()
  26. }
  27.  aboutToDisappear(): void {
  28.    this.breakpointSystem.unregister()
  29. }
  30.  build() {
  31.    Grid() {
  32.      ForEach(this.items, (item: MovieItem) => {
  33.        GridItem() {
  34.          Column({ space: 10 }) {
  35.            Image(item.img)
  36.             .borderRadius(10)
  37.            Text(item.title)
  38.             .width('100%')
  39.             .fontSize(20)
  40.             .fontWeight(600)
  41.         }
  42.       }
  43.     })
  44.   }
  45.   .columnsTemplate(new BreakPointType({
  46.      xs: '1fr 1fr',
  47.      sm: '1fr 1fr ',
  48.      md: '1fr 1fr 1fr ',
  49.      lg: '1fr 1fr 1fr 1fr '
  50.   }).getValue(this.currentBreakpoint))
  51.   .rowsGap(10)
  52.   .columnsGap(10)
  53.   .padding(10)
  54. }
  55. }

效果:

3. 栅格布局 Grid

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

比如:

img

参考栅格列数设置:

img

核心用法

优先级从上往下:

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

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

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

  1. @Entry
  2. @Component
  3. struct Demo11_login {
  4.  build() {
  5.    Stack() {
  6.      // 辅助用的栅格(顶层粉色区域)
  7.      GridRow({ gutter: 10, columns: { sm: 4, md: 8, lg: 12 } }) {
  8.        ForEach(Array.from({ length: 12 }), () => {
  9.          GridCol()
  10.           .width('100%')
  11.           .height('100%')
  12.           .backgroundColor('#baffa2b4')
  13.       })
  14.     }
  15.     .zIndex(2)
  16.     .height('100%')
  17.      // 内容区域
  18.      GridRow({
  19.        // TODO 分别设置不同断点的 列数
  20.        columns: {
  21.          sm: 4,
  22.          md: 8,
  23.          lg: 12
  24.       }
  25.     }) {
  26.        // 列
  27.        GridCol({
  28.          // TODO 分别设置不同断点的 所占列数
  29.          span: {
  30.            sm: 4,
  31.            md: 6,
  32.            lg: 8
  33.         },
  34.          // TODO 分别设置不同断点的 偏移
  35.          offset: {
  36.            md: 1,
  37.            lg: 2
  38.         }
  39.       }) {
  40.          Column() {
  41.            // logo+文字
  42.            LogoCom()
  43.            // 输入框 + 底部提示文本
  44.            InputCom()
  45.            // 登录+注册账号按钮
  46.            ButtonCom()
  47.         }
  48.       }
  49.     }
  50.     .width('100%')
  51.     .height('100%')
  52.     .backgroundColor('#ebf0f2')
  53.   }
  54. }
  55. }
  56. @Component
  57. struct LogoCom {
  58.  build() {
  59.    Column({ space: 5 }) {
  60.      Image($r('app.media.ic_logo'))
  61.       .width(80)
  62.      Text('登录界面')
  63.       .fontSize(23)
  64.       .fontWeight(900)
  65.      Text('登录账号以使用更多服务')
  66.       .fontColor(Color.Gray)
  67.   }
  68.   .margin({ top: 100 })
  69. }
  70. }
  71. @Component
  72. struct InputCom {
  73.  build() {
  74.    Column() {
  75.      Column() {
  76.        TextInput({ placeholder: '账号' })
  77.         .backgroundColor(Color.Transparent)
  78.        Divider()
  79.         .color(Color.Gray)
  80.        TextInput({ placeholder: '密码' })
  81.         .type(InputType.Password)
  82.         .backgroundColor(Color.Transparent)
  83.     }
  84.     .backgroundColor(Color.White)
  85.     .borderRadius(20)
  86.     .padding({ top: 10, bottom: 10 })
  87.      Row() {
  88.        Text('短信验证码登录')
  89.         .fontColor('#006af7')
  90.         .fontSize(14)
  91.        Text('忘记密码')
  92.         .fontColor('#006af7')
  93.         .fontSize(14)
  94.     }
  95.     .width('100%')
  96.     .justifyContent(FlexAlign.SpaceBetween)
  97.     .margin({ top: 10 })
  98.   }
  99.   .padding(5)
  100.   .margin({ top: 80 })
  101. }
  102. }
  103. @Component
  104. struct ButtonCom {
  105.  build() {
  106.    Column({ space: 10 }) {
  107.      Button('登录')
  108.       .width('90%')
  109.      Text('注册账号')
  110.       .fontColor('#006af7')
  111.       .fontSize(16)
  112.   }
  113.   .margin({ top: 60 })
  114. }
  115. }

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/842465
推荐阅读
相关标签
  

闽ICP备14008679号