【HarmonyOS】当list设置横向布局时,list高度默认撑满没有达到预期的高度自适应,可以通过onAreaChange动态修改高度。

【修改前】

【HarmonyOS】鸿蒙横向List高度适配_Text

@Entry
@Component
struct Page148 {
  build() {
    Column() {
      List() {
        ForEach(['北京', '杭州', '上海'], (item: string, index: number) => {
          ListItem() {
            Text(item).fontSize(24)
              .height(100 * (Math.floor(Math.random() * 3) + 1))//生成一个1到3 随机数,然后+100高度 测试
              .backgroundColor(Color.Pink)
              .margin(10)
          }
        })
      }
      .listDirection(Axis.Horizontal)
      .backgroundColor('#FFF1F3F5')
    }.width('100%')
    .height('100%')
  }
}

【修改后】

【HarmonyOS】鸿蒙横向List高度适配_Math_02

@Entry
@Component
struct Page148 {
  @State maxItemHeight: number = -1

  build() {
    Column() {
      List() {
        ForEach(['北京', '杭州', '上海'], (item: string, index: number) => {
          ListItem() {
            Text(item).fontSize(24)
              .height(100 * (Math.floor(Math.random() * 3) + 1))//生成一个1到3 随机数,然后+100高度 测试
              .backgroundColor(Color.Pink)
              .margin(10)
          }.onAreaChange((oldArea: Area, newArea: Area) => {
            if (this.maxItemHeight < newArea.height) {
              this.maxItemHeight = newArea.height as number
            }
          })
        })
      }
      .listDirection(Axis.Horizontal)
      .backgroundColor('#FFF1F3F5')
      .height(this.maxItemHeight == -1 ? undefined : this.maxItemHeight)
    }.width('100%')
    .height('100%')
  }
}