当前位置:首页 » 程序代码 » 正文

响应式布局之媒体查询布局:横屏与竖屏状态的监控,arkts

将上篇文章修改一下,用于媒体查询之监控横屏与竖屏状态。代码如下:

import { mediaquery } from '@kit.ArkUI'; //导入媒体查询模块

@Entry
@Component
struct Page8 {
  @State message: string = '';
  @State backColor: Color = Color.White
  //通过 matchMediasync 接口设置媒体查询条件
  //横屏条件 -- 源码来自 wb98.com
  private listener0: mediaquery.MediaQueryListener =
    this.getUIContext().getMediaQuery().matchMediaSync('(orientation: landscape)')
  //竖屏条件
  private listener9: mediaquery.MediaQueryListener =
    this.getUIContext().getMediaQuery().matchMediaSync('(orientation: portrait)')

  aboutToAppear(): void {
    //所有监听绑定事件
    this.listener0.on('change', (result: mediaquery.MediaQueryResult) => {
      if (result.matches) {
        this.backColor = Color.Yellow
        this.message = 'landscape 横屏'
      }
    })

    this.listener9.on('change', (result: mediaquery.MediaQueryResult) => {
      if (result.matches) {
        this.backColor = Color.Green
        this.message = 'portrait 竖屏'
      }
    })
  }

  aboutToDisappear(): void {
    //解绑监听
    this.listener0.off('change')
    this.listener9.off('change')
  }

  build() {

    Column() {

      Text(this.message)
        .fontSize(50)
        .fontWeight(FontWeight.Medium)
    }
    .width('100%')
    .height('100%')
    .backgroundColor(this.backColor)

  }
}


打赏 支付宝打赏 微信打赏

来源:济亨网

本文链接:https://www.wb98.com/post/379.html

arkts  鸿蒙  
    << 上一篇 下一篇 >>

    湘公网安备 43011102000514号 - 湘ICP备08100508号