文档开发者中心
我的
|

ArkUI (方舟UI框架)

UI

HarmonyOS 5

HarmonyOS Flex布局如何限制显示行数? (API12+)

HarmonyOS Flex布局如何限制显示行数? (API12+)

点赞
收藏
回复
1
分享
举报
浏览77 发布于2026-04-02 11:25未知归属地
全部评论
最多点赞
最新发布
最早发布

通过onAreaChange回调,收集各子项宽度和Flex组件自身宽度,通过自定义方法计算得出最大行数能容纳的子项个数,查看最后一行是否能放置折叠按钮,若不能,则削减子项个数,直到能为止。示例代码如下:

收起
自动换行
深色代码主题
复制
@Entry
@Component
struct FlexTest {
  @State message: string = 'Hello World';
  @State allDataList: string[] = ['1', '222', '33333', '44', '2', '222', '33333', '44', '1', '222', '33333', '44', '222', '33333']
  @State showDataList: string[] = []
  @State isShowAll: boolean = true
  private cutIndex: number = 0
  private flexWidth: number = 0
  private itemWidthList: number[] = []
  private isInit: boolean = false
  aboutToAppear(): void {
    this.initItemList()
  }

  initItemList() {
    this.showDataList = this.allDataList
    this.itemWidthList = new Array<number>(this.allDataList.length)
    for (let i = 0; i < this.itemWidthList.length; i++) {
      this.itemWidthList[i] = 0
    }
    this.isInit = false
  }

  isDrawFinish() {
    let isFinish = true;
    for (let i = 0; i < this.itemWidthList.length; i++) {
      if (this.itemWidthList[i] == 0) {
        isFinish = false
      }
    }
    if (this.flexWidth == 0) {
      isFinish = false;
    }

    if (isFinish) {
      this.isInit = true
      this.calculateCutIndex(3)
      this.transformExpendList(false)
    }
  }

  transformExpendList(showAll: boolean) {
    if (showAll) {
      this.isShowAll = true
      this.showDataList = this.allDataList
    } else {
      this.isShowAll = false
      this.showDataList = this.allDataList.slice(0, this.cutIndex)
    }
  }

  // maxLine指布局需要保留的最大行数
  calculateCutIndex(maxLine: number) {
    let layer = 1;
    let curLength = 0;
    for (let i = 0; i < this.itemWidthList.length; i++) {
      curLength += this.itemWidthList[i]
      if (curLength > this.flexWidth) {
        if (layer == maxLine) {
          curLength -= this.itemWidthList[i]
          this.cutIndex = i
          break;
        } else {
          layer += 1
          curLength = this.itemWidthList[i]
        }
      }
    }

    // 查看maxLine当前剩余的宽度是否足以容纳按钮,不能则掏空到能为止
    let buttonWidth = 40
    let empty = this.flexWidth - curLength
    while (empty <= buttonWidth) {
      empty += this.itemWidthList[this.cutIndex]
      this.cutIndex--
    }
  }
  build() {
    Column() {
      Flex({wrap: FlexWrap.Wrap, alignItems: ItemAlign.Center}) {
        ForEach(this.showDataList, (item: string, index: number) => {
          Text(item)
            .fontSize(20)
            .fontWeight(FontWeight.Bold)
            .fontColor(Color.Black)
            .backgroundColor(Color.Gray)
            .borderRadius(10)
            .padding(8)
            .margin(5)
            .id(`item_${index}`)
            .onAreaChange((oldValue: Area, newValue: Area) => {
              if (!this.isInit && newValue.width != 0) {
                this.itemWidthList[index] = Number(newValue.width) + 10 // item宽度加上两边margin
                this.isDrawFinish()
              }
            })
        })
        Button() {
          Text(this.isShowAll ? '^' : 'v')
            .padding(10)
            .fontColor(Color.White)
            .borderRadius(5)
        }
        .width(40)
        .onClick(() => {
          this.transformExpendList(!this.isShowAll)
        })
      }
      .onAreaChange((oldValue: Area, newValue: Area) => {
        if (!this.isInit && newValue.width != 0) {
          this.flexWidth = Number(newValue.width)
          this.isDrawFinish()
        }
      })
      .backgroundColor("#f1f3f5")
      .id("flex")
      .width("50%")
    }
    .height('100%')
    .width('100%')
    .justifyContent(FlexAlign.Start)
  }
}
展开全部
1楼回复于2026-04-02 11:25 未知归属地
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要提问题

了解社区公约,与您携手共创和谐专业的开发者社区。