鸿蒙Next-一次开发多端部署-基于媒体查询

当我们想要实现一次开发,多端部署的时候,可以基于媒体查询来实现,

1针对设备和应用的属性信息(比如显示区域、深浅色、分辨率),设计出相匹配的布局。
2当屏幕发生动态改变时(比如分屏、横竖屏切换),同步更新应用的页面布局。

我们对该媒体查询进行封装

整合步骤为:导入模块 ---> 创建监听器 ---> 注册监听器 ---> 移除监听器

封装示例代码如下:

import { mediaquery } from '@kit.ArkUI'

interface Breakpoint {
  name: string
  size: number
  mediaQueryListener?: mediaquery.MediaQueryListener
}

export const BreakpointKey: string = 'currentBreakpoint'

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: string
      if (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 = breakpoint
      AppStorage.set<string>(BreakpointKey, this.currentBreakpoint)
      console.log('on current breakpoint: ' + this.currentBreakpoint)
    }
  }
}

核心用法:
1导入 BreakpointSystem
2实例化BreakpointSystem
3aboutToAppear中注册监听事件 aboutToDisappear中移除监听事件
4通过 AppStorage,结合 获取断点值即可

示例代码如下:

// 1. 导入断点查询类
import { BreakpointSystem, BreakpointKey} from '../common/BreakpointSystem'

@Entry
@Component
struct Demo10 {

  // 5. 获取断点值
  @StorageProp(BreakpointKey) currentBreakpoint: string = 'sm'

  // 2. 实例化断点查询类
  breakpointSystem = new BreakpointSystem()

  // 3. 注册事件监听
  aboutToAppear(): void {
    this.breakpointSystem.register()
  }

  // 4. 移除事件监听
  aboutToDisappear(): void {
    this.breakpointSystem.unregister()
  }

  build() {
    RelativeContainer() {
      Text(this.currentBreakpoint)
        .id('Demo10HelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
    }
    .height('100%')
    .width('100%')
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值