实现容器高度自适应鸿蒙示例代码

鸿蒙场景化示例代码技术工程师
发布于 2025-3-14 15:30
浏览
0收藏

本文原创发布在华为开发者社区

介绍

该示例实现了List横向滑动容器高度自适应,通过List模拟美团首页菜单横向滚动高度自适应效果。

实现容器高度自适应源码链接

效果预览

实现容器高度自适应鸿蒙示例代码-鸿蒙开发者社区

使用说明

安装到手机后不会在桌面生成桌面图标,点击卡片即可进入本应用。

实现思路

  • 在list组件区域变化时获取宽度和高度
List({ scroller: this.listScroller }) {
  ...
}
...
//获取高度宽度
.onAreaChange((_, n) => {
  if (!this.containerWidth) {
    this.containerWidth = Number(n.width)
    this.containerHeight = Number(n.height)
    this.containerMaxHeight = this.containerHeight
    // 最后一页高度即为最小高度 // 20-行间距 3-行数
    this.containerMinHeight =
      (this.containerHeight - 20) / 3 * this.lastPageLines + 10 * (this.lastPageLines - 1)
  }
})
//实现容器高度自适应
.onWillScroll((x)=>{
  this.updateContainerHeight(x)
})
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 通过updateContainerHeight方法计算高度变化,实现横向滚动高度自适应效果。
updateContainerHeight(x: number) {
  let offsetX = this.listScroller.currentOffset().xOffset + x - this.containerWidth * (this.pageSize - 2)
  if (offsetX > 0) {
    let h = offsetX / this.containerWidth * (this.containerMaxHeight - this.containerMinHeight)
    // 根据横向偏移距离等比计算高度变化
    this.containerHeight = this.containerMaxHeight - h
  } else {
    this.containerHeight = this.containerMaxHeight
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

分类
收藏
回复
举报
回复
    相关推荐