HarmonyOS NEXT实战:瀑布流和懒加载

简介: 本教程介绍如何在HarmonyOS应用中实现瀑布流布局,包含图片与文字展示,并通过懒加载优化性能。内容涵盖数据源构建、自定义组件开发及页面集成,适合初学者掌握HarmonyOS UI开发技巧。

HarmonyOS Next实战##HarmonyOS应用开发##教育

目标:实现瀑布流图片和文字,并通过懒加载加载瀑布流子项。

实现思路:

  1. 创建Card模型
  2. 创建WaterFlowDataSource 数据源
  3. 定制WaterFlowItemComponent自定义组件
  4. 在页面实现WaterFlow和LazyForEach循环

WaterFlow
瀑布流容器,由“行”和“列”分割的单元格所组成,通过容器自身的排列规则,将不同大小的“项目”自上而下,如瀑布般紧密布局。
仅支持FlowItem子组件,支持渲染控制类型(if/else、ForEach、LazyForEach和Repeat)。

实战:
WaterFlowDataSource

// 实现IDataSource接口的对象,用于瀑布流组件加载数据
export class WaterFlowDataSource implements IDataSource {
   
  private dataArray: Card[] = [];
  private listeners: DataChangeListener[] = [];

  constructor() {
   
    this.dataArray.push({
   
      image: $r('app.media.img_1'),
      imageWidth: 162,
      imageHeight: 130,
      text: 'Ice cream is made with carrageenan …',
      buttonLabel: 'View article'
    });
    this.dataArray.push({
   
      image: $r('app.media.img_2'),
      imageWidth: '100%',
      imageHeight: 117,
      text: 'Is makeup one of your daily esse …',
      buttonLabel: 'View article'
    });
    this.dataArray.push({
   
      image: $r('app.media.img_3'),
      imageWidth: '100%',
      imageHeight: 117,
      text: 'Coffee is more than just a drink: It’s …',
      buttonLabel: 'View article'
    });
    this.dataArray.push({
   
      image: $r('app.media.img_4'),
      imageWidth: 162,
      imageHeight: 130,
      text: 'Fashion is a popular style, especially in …',
      buttonLabel: 'View article'
    });
    this.dataArray.push({
   
      image: $r('app.media.img_5'),
      imageWidth: '100%',
      imageHeight: 206,
      text: 'Argon is a great free UI packag …',
      buttonLabel: 'View article'
    });
  }

  // 获取索引对应的数据
  public getData(index: number): Card {
   
    return this.dataArray[index];
  }

  // 通知控制器数据重新加载
  notifyDataReload(): void {
   
    this.listeners.forEach(listener => {
   
      listener.onDataReloaded();
    })
  }

  // 通知控制器数据增加
  notifyDataAdd(index: number): void {
   
    this.listeners.forEach(listener => {
   
      listener.onDataAdd(index);
    })
  }

  // 通知控制器数据变化
  notifyDataChange(index: number): void {
   
    this.listeners.forEach(listener => {
   
      listener.onDataChange(index);
    })
  }

  // 通知控制器数据删除
  notifyDataDelete(index: number): void {
   
    this.listeners.forEach(listener => {
   
      listener.onDataDelete(index);
    })
  }

  // 通知控制器数据位置变化
  notifyDataMove(from: number, to: number): void {
   
    this.listeners.forEach(listener => {
   
      listener.onDataMove(from, to);
    })
  }

  //通知控制器数据批量修改
  notifyDatasetChange(operations: DataOperation[]): void {
   
    this.listeners.forEach(listener => {
   
      listener.onDatasetChange(operations);
    })
  }

  // 获取数据总数
  public totalCount(): number {
   
    return this.dataArray.length;
  }

  // 注册改变数据的控制器
  registerDataChangeListener(listener: DataChangeListener): void {
   
    if (this.listeners.indexOf(listener) < 0) {
   
      this.listeners.push(listener);
    }
  }

  // 注销改变数据的控制器
  unregisterDataChangeListener(listener: DataChangeListener): void {
   
    const pos = this.listeners.indexOf(listener);
    if (pos >= 0) {
   
      this.listeners.splice(pos, 1);
    }
  }

  // 增加数据
  public add1stItem(card: Card): void {
   
    this.dataArray.splice(0, 0, card);
    this.notifyDataAdd(0);
  }

  // 在数据尾部增加一个元素
  public addLastItem(card: Card): void {
   
    this.dataArray.splice(this.dataArray.length, 0, card);
    this.notifyDataAdd(this.dataArray.length - 1);
  }

  public addDemoDataAtLast(): void {
   
    this.dataArray.push({
   
      image: $r('app.media.img_1'),
      imageWidth: 162,
      imageHeight: 130,
      text: 'Ice cream is made with carrageenan …',
      buttonLabel: 'View article'
    });
    this.dataArray.push({
   
      image: $r('app.media.img_2'),
      imageWidth: '100%',
      imageHeight: 117,
      text: 'Is makeup one of your daily esse …',
      buttonLabel: 'View article'
    });
    this.dataArray.push({
   
      image: $r('app.media.img_3'),
      imageWidth: '100%',
      imageHeight: 117,
      text: 'Coffee is more than just a drink: It’s …',
      buttonLabel: 'View article'
    });
    this.dataArray.push({
   
      image: $r('app.media.img_4'),
      imageWidth: 162,
      imageHeight: 130,
      text: 'Fashion is a popular style, especially in …',
      buttonLabel: 'View article'
    });
    this.dataArray.push({
   
      image: $r('app.media.img_5'),
      imageWidth: '100%',
      imageHeight: 206,
      text: 'Argon is a great free UI packag …',
      buttonLabel: 'View article'
    });
  }

  // 在指定索引位置增加一个元素
  public addItem(index: number, card: Card): void {
   
    this.dataArray.splice(index, 0, card);
    this.notifyDataAdd(index);
  }

  // 删除第一个元素
  public delete1stItem(): void {
   
    this.dataArray.splice(0, 1);
    this.notifyDataDelete(0);
  }

  // 删除第二个元素
  public delete2ndItem(): void {
   
    this.dataArray.splice(1, 1);
    this.notifyDataDelete(1);
  }

  // 删除最后一个元素
  public deleteLastItem(): void {
   
    this.dataArray.splice(-1, 1);
    this.notifyDataDelete(this.dataArray.length);
  }

  // 在指定索引位置删除一个元素
  public deleteItem(index: number): void {
   
    this.dataArray.splice(index, 1);
    this.notifyDataDelete(index);
  }

  // 重新加载数据
  public reload(): void {
   
    this.dataArray.splice(1, 1);
    this.dataArray.splice(3, 2);
    this.notifyDataReload();
  }
}

export interface Card {
   
  image: Resource //图片
  imageWidth: Length //图片宽度
  imageHeight: Length //图片高度
  text: string //文字
  buttonLabel: string //按钮文字
}

WaterFlowItemComponent

import {
    Card } from "./WaterFlowDataSource";

// @Reusable
@Component
export struct WaterFlowItemComponent {
   
  @Prop item: Card

  // 从复用缓存中加入到组件树之前调用,可在此处更新组件的状态变量以展示正确的内容
  aboutToReuse(params: Record<string, Card>) {
   
    this.item = params.item;
    console.info('Reuse item:' + JSON.stringify(this.item));
  }

  aboutToAppear() {
   
    console.info('new item:' + JSON.stringify(this.item));
  }

  build() {
   
    if (this.item.imageWidth == '100%') {
   
      Column() {
   
        Image(this.item.image)
          .width(this.item.imageWidth)
          .height(this.item.imageHeight)
        Column() {
   
          Text(this.item.text)
            .fontWeight(400)
            .fontColor('#32325D')
            .fontSize(14)
            .lineHeight(18)
          Text(this.item.buttonLabel)
            .fontWeight(700)
            .fontColor('#5E72E4')
            .fontSize(12)
            .lineHeight(17)
        }
        .width('100%')
        .padding(12)
        .layoutWeight(1)
        .alignItems(HorizontalAlign.Start)
        .justifyContent(FlexAlign.SpaceBetween)
      }
      .width('100%')
      .height('100%')
      .alignItems(HorizontalAlign.Start)
    } else {
   
      Row() {
   
        Image(this.item.image)
          .width(this.item.imageWidth)
          .height(this.item.imageHeight)

        Column() {
   
          Text(this.item.text)
            .fontWeight(400)
            .fontColor('#32325D')
            .fontSize(14)
            .lineHeight(18)
          Text(this.item.buttonLabel)
            .fontWeight(700)
            .fontColor('#5E72E4')
            .fontSize(12)
            .lineHeight(17)
        }
        .height('100%')
        .layoutWeight(1)
        .alignItems(HorizontalAlign.Start)
        .padding(12)
        .justifyContent(FlexAlign.SpaceBetween)
      }
      .width('100%')
      .height('100%')
    }
  }
}

WaterFlowDemoPage

import {
    Card, WaterFlowDataSource } from './WaterFlowDataSource';
import {
    WaterFlowItemComponent } from './WaterFlowItemComponent';

@Entry
@Component
export struct WaterFlowDemoPage {
   
  minSize: number = 80;
  maxSize: number = 180;
  fontSize: number = 24;
  scroller: Scroller = new Scroller();
  dataSource: WaterFlowDataSource = new WaterFlowDataSource();
  dataCount: number = this.dataSource.totalCount();
  private itemHeightArray: number[] = [];
  @State sections: WaterFlowSections = new WaterFlowSections();
  sectionMargin: Margin = {
   
    top: 10,
    left: 20,
    bottom: 10,
    right: 20
  };

  // 设置FlowItem的高度数组
  setItemSizeArray() {
   
    this.itemHeightArray.push(130);
    this.itemHeightArray.push(212);
    this.itemHeightArray.push(212);
    this.itemHeightArray.push(130);
    this.itemHeightArray.push(268);
  }

  aboutToAppear() {
   
    this.setItemSizeArray();
    this.addSectionOptions(true);
    for (let index = 0; index < 10; index++) {
   
      this.dataSource.addDemoDataAtLast();
      this.setItemSizeArray();
      this.addSectionOptions();
    }
  }

  addSectionOptions(isFirstAdd: boolean = false) {
   
    this.sections.push({
   
      itemsCount: 1,
      crossCount: 1,
      margin: isFirstAdd ? {
   
        top: 20,
        left: 20,
        bottom: 10,
        right: 20
      } : this.sectionMargin,
      onGetItemMainSizeByIndex: (index: number) => {
   
        return 130;
      }
    })
    this.sections.push({
   
      itemsCount: 2,
      crossCount: 2,
      rowsGap: '20vp',
      margin: this.sectionMargin,
      onGetItemMainSizeByIndex: (index: number) => {
   
        return 212;
      }
    })
    this.sections.push({
   
      itemsCount: 1,
      crossCount: 1,
      margin: this.sectionMargin,
      onGetItemMainSizeByIndex: (index: number) => {
   
        return 130;
      }
    })
    this.sections.push({
   
      itemsCount: 1,
      crossCount: 1,
      rowsGap: '20vp',
      columnsGap: '20vp',
      margin: this.sectionMargin,
      onGetItemMainSizeByIndex: (index: number) => {
   
        return 268;
      }
    })
  }

  build() {
   
    Column({
    space: 2 }) {
   
      WaterFlow({
    scroller: this.scroller, sections: this.sections }) {
   
        LazyForEach(this.dataSource, (item: Card, index: number) => {
   
          FlowItem() {
   
            WaterFlowItemComponent({
    item: item })
          }
          .width('100%')
          .backgroundColor(Color.White)
          .borderRadius(6)
          .clip(true)
        }, (item: Card, index: number) => index.toString())
      }
      // .columnsTemplate('1fr 1fr') // 瀑布流使用sections参数时该属性无效
      .columnsGap(14)
      .rowsGap(20)
      .backgroundColor('#F8F9FE')
      .width('100%')
      .height('100%')
      .layoutWeight(1)
    }
  }
}
目录
相关文章
|
监控 JavaScript 编译器
从“天书”到源码:HarmonyOS NEXT 崩溃堆栈解析实战指南
本文详解如何利用 hiAppEvent 监控并获取 sourcemap、debug so 等核心产物,剖析了 hstack 工具如何将混淆的 Native 与 ArkTS 堆栈还原为源码,助力开发者掌握异常分析方法,提升应用稳定性。
1325 104
|
开发者 容器
鸿蒙应用开发从入门到实战(十四):ArkUI组件Column&Row&线性布局
ArkUI提供了丰富的系统组件,用于制作鸿蒙原生应用APP的UI,本文主要讲解Column和Row组件的使用以及线性布局的方法。
1083 12
|
JavaScript 开发者 索引
鸿蒙应用开发从入门到实战(九):ArkTS渲染控制
ArkTS拓展了TypeScript,可以结合ArkUI进行渲染控制,是的界面设计具有可编程性。本文简要描述鸿蒙应用开发中的条件渲染和循环渲染。
503 5
|
API 数据处理
鸿蒙应用开发从入门到实战(十三):ArkUI组件Slider&Progress
ArkUI提供了丰富的系统组件,用于制作鸿蒙原生应用APP的UI,本文主要讲解滑块Slider和进度条Progress组件的使用。
560 1
|
移动开发 前端开发 Android开发
【02】建立各项目录和页面标准化产品-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【02】建立各项目录和页面标准化产品-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
2312 12
【02】建立各项目录和页面标准化产品-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
|
移动开发 JavaScript 应用服务中间件
【06】优化完善落地页样式内容-精度优化-vue加vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【06】优化完善落地页样式内容-精度优化-vue加vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
1451 5
【06】优化完善落地页样式内容-精度优化-vue加vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
|
移动开发 Rust JavaScript
【01】首页建立-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【01】首页建立-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
1506 4
【01】首页建立-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
|
数据安全/隐私保护 开发者
鸿蒙应用开发从入门到实战(十一):ArkUI组件Text&TextInput
ArkUI提供了丰富的系统组件,用于制作鸿蒙原生应用APP的UI,本文主要讲解文本组件Text和TextInput的使用。
834 3
|
存储 缓存 5G
鸿蒙 HarmonyOS NEXT端云一体化开发-云存储篇
本文介绍用户登录后获取昵称、头像的方法,包括通过云端API和AppStorage两种方式,并实现上传头像至云存储及更新用户信息。同时解决图片缓存问题,添加上传进度提示,支持自动登录判断,提升用户体验。
623 1
|
移动开发 Android开发
【03】建立隐私关于等相关页面和内容-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【03】建立隐私关于等相关页面和内容-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
806 0

热门文章

最新文章