HarmonyOS 网格布局是否可以自适应高度?根据数据的数量 自适应高度?

网格布局是否可以自适应高度?根据数据的数量 自适应高度

阅读 599
1 个回答

通过计算展示的行数rowCount,根据rowCount得出GridHeight、GridRowsTemplate。参考demo:

@Entry
@Component
struct ABPage {
  @State message: string = 'Hello World';
  private controller: TextInputController = new TextInputController()
  @State simpleList: Array<string> = ['one', 'two', 'three', 'one', 'two', 'three','one', 'two', 'three', 'one', 'two',];
  getCategoryRowCount() {
    return Math.ceil(this.simpleList.length / 3);
  }
  getCategoryRowTmpl() {
    const count = this.getCategoryRowCount();
    const arr: string[] = new Array(count || 1).fill('1fr');
    console.log('tmpl ', arr.join(' '))
    return arr.join(' ');
  }
  getCategoryViewHeight() {
    return `${50 * this.getCategoryRowCount()}vp`;
  }
  build() {
    Column() {
      Column() {
        Grid() {
          ForEach(this.simpleList, (item: string) => {
            this.gridItemBuilder(item)
          })
        }
        .height(this.getCategoryViewHeight())
        .rowsTemplate(this.getCategoryRowTmpl())
        .columnsTemplate('1fr 1fr 1fr ')
      }
      // .height("15%")
      .backgroundColor('#ff02194c')
      .justifyContent(FlexAlign.SpaceEvenly)
      Column() {
        List() {
          ForEach(this.simpleList, (item: string) => {
            this.gridItemBuilder(item)
          })
        }
      }
      .backgroundColor('#ffcff10c')
      .height("100%")

    }
    .width('94%')
    .height('80%')
    .borderRadius(10)
    .backgroundColor('#ff8f1616')
    .justifyContent(FlexAlign.Start)
    .margin({ top: '10%', left: '3%', right: '3%',bottom:'10%' })
  }

  @Builder
  gridItemBuilder(content: string) {
    GridItem() {
      Column() {
        Text(content)
          .fontSize(15)
      }
      .justifyContent(FlexAlign.Center)
      .borderRadius(10)
      .backgroundColor('#ffeabe4f')
      .height('25vp')
      .width('100%')
      .margin({ top: '5vp' })
      .onClick(() => {

      })
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进