• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16class MyDataSource implements IDataSource {
17  private dataArray: number[] = [];
18
19  public pushData(data: number): void {
20    this.dataArray.push(data);
21  }
22
23  //数据源的数据总量
24  public totalCount(): number {
25    return this.dataArray.length;
26  }
27
28  public getData(index: number): number {
29    return this.dataArray[index];
30  }
31
32  registerDataChangeListener(listener: DataChangeListener): void {
33  }
34
35  unregisterDataChangeListener(listener: DataChangeListener): void {
36  }
37}
38
39@Component
40export struct GridLazyForEachView {
41  // 数据源
42  private data: MyDataSource = new MyDataSource();
43
44  aboutToAppear() {
45    for (let i = 1; i < 1000; i++) {
46      this.data.pushData(i);
47    }
48  }
49
50  build() {
51    Column({ space: 5 }) {
52      Grid() {
53        LazyForEach(this.data, (item: number) => {
54          GridItem() {
55            // 使用可复用组件
56            ReusableChildComponent({ item: item });
57          }
58        }, (item: string) => item)
59      }
60      .cachedCount(2)
61      .columnsTemplate("1fr 1fr 1fr")
62      .columnsGap(10)
63      .rowsGap(10)
64      .height(500)
65      .backgroundColor(0xFAEEE0)
66    }
67  }
68}
69
70@Reusable
71@Component
72struct ReusableChildComponent {
73  @State item: number = 0;
74
75  aboutToReuse(params: Record<string, number>) {
76    this.item = params.item;
77  }
78
79  build() {
80    Column() {
81      Image($r('app.media.icon'))
82        .objectFit(ImageFit.Fill)
83        .layoutWeight(1)
84      Text(`图片${this.item}`)
85        .fontSize(16)
86        .textAlign(TextAlign.Center)
87    }
88    .width("100%")
89    .height(120)
90    .backgroundColor(0xF9CF93)
91  }
92}