讨论广场 问答详情
使用列表数据构建List布局,根据数据类型分别执行对应逻辑,如果是广告类型,使用NodeContainer进行预占位。这是为什么?有没有相关的演示代码帮我分析一下呢?
guorongcui 2026-06-28 00:05:12
28 评论 分享
harmonyos

当NodeContainer渲染时,发起请求获取广告信息等数据。解析数据明确广告类型后,构建具体的广告布局,比如图文布局、视频布局等。对于初学者来说,学习鸿蒙开发如何来入门比较好?

28 评论 分享
写回答
全部评论(1)
  1. 使用列表数据构建List布局,根据数据类型分别执行对应逻辑,如果是广告类型,使用NodeContainer进行预占位。
  2. 当NodeContainer渲染时,发起请求获取广告信息等数据。解析数据明确广告类型后,构建具体的广告布局,比如图文布局、视频布局等。
  3. 布局构建完成后,返回rootNode实现组件上树,最后在容器中渲染显示。

开发步骤

  1. 加载列表数据:模拟从服务器端获取列表数据,分别生成列表数据对象和广告数据对象。

     
    1. aboutToAppear() {
        for (let i = 0; i <= 100; i++) {
          let id = i.toString();
          if (i % 7 === 6) {
            this.data.pushData(new CardData(true, id));
            try {
              this.idList.add(id);
            } catch (error) {
              let err = error as BusinessError
              if (err.code) {
                hilog.error(0x0000, 'ImperativeView', 'Failed to add id. Cause: %{public}s', JSON.stringify(err) ?? '');
              }
            }
          } else {
            this.data.pushData(new CardData(false, id));
          }
        }
      }

      示例代码中用CardData(true, id)表示广告数据对象。

    2. export class CardData {
        private id: string = '';
        private mIsAdCard: boolean = false;
      
        constructor(isAdCard: boolean, id: string) {
          this.mIsAdCard = isAdCard;
          this.id = id;
        }
        // ...
      }

      构建广告组件:封装广告组件AdComponent,它通过模拟获取的广告类型去判断,进一步构建图文广告组件,或视频广告组件。

    3. @Builder
      export function adBuilder(param: AdParams) {
        AdComponent({ params: param });
      }
      
      @Component
      struct AdComponent {
        params ?: AdParams;
        closeAdDialogController: CustomDialogController = new CustomDialogController({
          builder: CloseAdDialog({
            adId: this.params!.id
          }),
          backgroundBlurStyle: BlurStyle.COMPONENT_THICK,
        });
      
        build() {
          if (this.params!.isVideo) {
            videoAdBuilder(this.closeAdDialogController);
          } else {
            picAdBuilder(this.closeAdDialogController);
          }
        }
      }

       

    2026-06-28 00:05:54