一个 Scroll 撑起整个首页:HarmonyOS 7 懒加载布局把网格、瀑布流、吸顶分组装进一次滚动

0 阅读5分钟

鸿蒙开发热点系列 · 第 14 篇 | 基于 HarmonyOS 7(API 26.0.0)

电商首页上面是 4×2 的分类宫格,中间一排推荐列表,下面是无限瀑布流;相册是按月分组、月份标题吸顶的九宫格。以前在鸿蒙上做这种页面,要么 List/Grid/WaterFlow 互相嵌套、处理手势冲突,要么全塞进 Scroll、一次性把几百个子组件全建出来。HarmonyOS 7(API 26.0.0)把懒加载布局容器补齐成了三件套:LazyColumnLayout、LazyVGridLayout、LazyVWaterFlowLayout。这篇只讲两件事:一个滚动容器里怎么混排三种布局,以及分组标题吸顶 + 触底加载的写法和几个会直接崩溃的坑。

一、三件套是什么:只管“按需建”,不管“滚”

官方的定义很干脆:懒加载布局容器嵌在可滚动父组件(Scroll、List、WaterFlow)里面,本身不滚动,滚动由父组件统一处理;它只创建、布局父组件可视区域内的子组件,并在帧间空闲时预加载上下各半屏的内容。好处是首帧快、内存省,而且所有区域共享一次滚动,不存在滚动嵌套的手势冲突。

LazyVGridLayoutLazyVWaterFlowLayoutLazyColumnLayout
起始版本API 1926.0.026.0.0
布局垂直网格垂直瀑布流垂直线性
列数 / 列间距columnsTemplate / columnsGap同左不支持
行间距rowsGaprowsGapspace
header / footer / sticky26.0.0 起支持支持支持
嵌套其他懒加载容器不支持不支持支持

记住最后一行:只有 LazyColumnLayout 能当“外壳”,里面再套网格、瀑布流或它自己;网格和瀑布流都是叶子。

二、混排模板:宫格 + 列表 + 瀑布流,一次滚动

LazyColumnLayout 和 LazyVWaterFlowLayout 需要从 @kit.ArkUI 导入。每个区域用自己的数据源(实现 IDataSource,配合 LazyForEach),不同业务模块的数据互不耦合:

import {
  LengthMetrics,
  LazyColumnLayout, LazyColumnLayoutAttribute,
  LazyVWaterFlowLayout, LazyVWaterFlowLayoutAttribute
} from '@kit.ArkUI';

class NumSource implements IDataSource {
  private listeners: DataChangeListener[] = [];
  private data: number[] = [];
  totalCount(): number { return this.data.length; }
  getData(index: number): number { return this.data[index]; }
  registerDataChangeListener(l: DataChangeListener): void {
    if (this.listeners.indexOf(l) < 0) { this.listeners.push(l); }
  }
  unregisterDataChangeListener(l: DataChangeListener): void {
    const pos = this.listeners.indexOf(l);
    if (pos >= 0) { this.listeners.splice(pos, 1); }
  }
  push(v: number): void {
    this.data.push(v);
    this.listeners.forEach(l => l.onDataAdd(this.data.length - 1));
  }
}

@Entry
@Component
struct HomeFeed {
  private cats: NumSource = new NumSource();   // 分类宫格
  private recs: NumSource = new NumSource();   // 推荐列表
  private goods: NumSource = new NumSource();  // 商品瀑布流

  aboutToAppear(): void {
    for (let i = 0; i < 8; i++) { this.cats.push(i); }
    for (let i = 0; i < 3; i++) { this.recs.push(i); }
    for (let i = 0; i < 60; i++) { this.goods.push(i); }
  }

  @Builder
  SectionHeader(title: string) {
    Text(title).fontSize(16).fontWeight(FontWeight.Bold)
      .width('100%').height(44).padding({ left: 16 })
      .backgroundColor(Color.White)
  }

  build() {
    Scroll() {
      LazyColumnLayout() {
        // 区域一:4 列分类宫格
        LazyVGridLayout() {
          LazyForEach(this.cats, (i: number) => {
            Text(`分类${i}`).height(64).textAlign(TextAlign.Center)
          }, (i: number) => `cat_${i}`)
        }
        .columnsTemplate('1fr 1fr 1fr 1fr')
        .rowsGap(LengthMetrics.vp(8))
        .columnsGap(LengthMetrics.vp(8))

        // 区域二:推荐列表
        LazyColumnLayout() {
          LazyForEach(this.recs, (i: number) => {
            Text(`推荐 ${i}`).width('100%').height(56).padding({ left: 16 })
          }, (i: number) => `rec_${i}`)
        }
        .space(LengthMetrics.vp(6))
        .header(this.SectionHeader('为你推荐'))

        // 区域三:双列瀑布流,标题吸顶
        LazyVWaterFlowLayout() {
          LazyForEach(this.goods, (i: number) => {
            Column() { Text(`商品 ${i}`) }
              .width('100%').height(120 + (i * 37) % 100)  // 卡片自身可以定高
              .backgroundColor('#E8EAF6').borderRadius(8)
          }, (i: number) => `goods_${i}`)
        }
        .columnsTemplate('1fr 1fr')
        .rowsGap(LengthMetrics.vp(10))
        .columnsGap(LengthMetrics.vp(10))
        .header(this.SectionHeader('猜你喜欢'))
        .sticky(StickyStyle.Header)
        .onVisibleIndexesChange((start: number, end: number) => {
          // 触底前 20 条就追加,用户感觉不到“加载中”
          if (end + 20 >= this.goods.totalCount()) {
            const n = this.goods.totalCount();
            for (let i = n; i < n + 40; i++) { this.goods.push(i); }
          }
        })
      }
      .space(LengthMetrics.vp(12))
    }
    .scrollable(ScrollDirection.Vertical)   // 必须竖直,否则直接崩
    .width('100%')
    .height('100%')
  }
}

几个要点:

  • header / footer 用 @Builder 传入,sticky 有三种:StickyStyle.Header(分组标题吸顶)、StickyStyle.Footer(汇总/操作栏吸底)、StickyStyle.BOTH。官方相册示例正是外层 LazyColumnLayout 里 LazyForEach 出多个 LazyVGridLayout,每个月一组、header + sticky(StickyStyle.Header) 让月份标题吸顶,外层 footer 显示“已经到底了”。
  • 触底加载用 onVisibleIndexesChange:回调给出可视区域的起止索引;容器里没有子组件或没有可见子组件时,start、end 都是 -1,判断时别把 -1 当成“到底了”。
  • columnsTemplate 支持 'repeat(auto-fill, 80vp)' 这类写法,PC/平板宽屏上自动多列,不用自己算断点。
  • 设了 sticky 后,因浮点精度滚动中偶尔会出现细缝,官方建议给组件加 pixelRound 向下取整解决。

三、四个坑:有两个是直接崩溃

  1. 父容器方向必须是竖直。List 要 listDirection(Axis.Vertical),Scroll 要 ScrollDirection.Vertical,WaterFlow 要 FlexDirection.Column。方向不对时,List/Scroll 下三种容器都会导致应用崩溃;WaterFlow 横向时 LazyColumnLayout、LazyVWaterFlowLayout 会崩,LazyVGridLayout 不崩但懒加载失效;FlexDirection.ColumnReverse 会显示异常。
  2. 懒加载会“悄悄失效”:List 设了 lanes、chainAnimation、scrollSnapAlign 任意一个,或 WaterFlow 是多列模式 / 多列分段,懒加载都不再生效——不报错,只是又回到一次性全建,性能问题会在数据量大时才暴露。想要瀑布流,就用 LazyVWaterFlowLayout 自己出列,别让外层 WaterFlow 多列。
  3. 别给懒加载容器本身定高:height、constraintSize 的 min/maxHeight、aspectRatio、layoutWeight 等会导致显示异常或无法滚动,它们的高度要随内容撑开(子组件定高没问题)。
  4. 父组件要有主轴尺寸:父组件没设高度时容器会被内容撑满,所有子组件全量加载——等于没懒加载。上面模板里 Scroll 设了 height('100%'),就是为此。

小结

把“滚动”和“按需创建”拆开,是这三件套的核心思路:外层只放一个竖直 Scroll(或 List),里面用 LazyColumnLayout 当骨架,按区域塞 LazyVGridLayout、LazyVWaterFlowLayout,再用 header + sticky 做分组、onVisibleIndexesChange 做触底加载。首页、相册、信息流这三类页面,基本都能用这一个模板改出来。升级到 26.0.0 的项目,值得把以前的“Scroll + ForEach 全量建”和多层滚动嵌套挨个换掉。

参考来源

  1. 华为开发者联盟:创建懒加载布局(LazyColumnLayout/LazyVGridLayout/LazyVWaterFlowLayout),developer.huawei.com/consumer/cn… (2026-11-16 查阅)
  2. 华为开发者联盟:LazyVGridLayout API 参考,developer.huawei.com/consumer/cn… (2026-11-16 查阅)
  3. 华为开发者联盟:HarmonyOS 26.0.1 版本概览(2026-11-10 发布 Beta1),developer.huawei.com/consumer/cn… (2026-11-16 查阅)