鸿蒙Next网格布局Grid简单使用

2025-06-27 22:46:21
104次阅读
0个评论

网格布局是由“行”和“列”分割的单元格所组成,通过指定“项目”所在的单元格做出各种各样的布局。网格布局具有较强的页面均分能力,子组件占比控制能力,是一种重要自适应布局,其使用场景有九宫格图片展示、日历、计算器等。 以下通过两种创建网格的方式演示: 1.固定行列分割比例,这种方式,可以让网格子布局按比例充满 2.通过设置最大行/列,最小列/行限制子布局,这样可以根据屏幕的宽高,动态的展示 演示.gif

@Entry
@ComponentV2
struct gridTest {
  @Local numbers: String[] = ['0', '1', '2', '3', '4', '5', '6', '7', '8'];
  @Local gridWidth:number=300;
  @Local gridHeight:number=300;
  build() {
    Column({ space: 10 }) {
      Row(){
        Button('宽增大').onClick(()=>{
          this.gridWidth+=10
        })
        Button('高增大').onClick(()=>{
          this.gridHeight+=10
        })
        Button('宽减小').onClick(()=>{
          this.gridWidth-=10
          this.gridHeight-=10
        })
        Button('高减小').onClick(()=>{
          this.gridHeight-=10
        })
      }
      Grid() {
        ForEach(this.numbers, (item: string) => {
          GridItem() {
            Text(item)
              .fontSize(16)
              .backgroundColor(0xF9CF93)
              .width(60)
              .height('100%')
              .textAlign(TextAlign.Center)
          }
        })
      }
      .columnsTemplate('1fr 1fr 1fr')
      .rowsTemplate('1fr 1fr 1fr')
      .columnsGap(10)
      .rowsGap(10)
      .width(this.gridWidth)
      .backgroundColor(0xFAEEE0)
      .height(this.gridHeight)
      Text('固定行列')
      Grid() {
        ForEach(this.numbers, (item: string) => {
          GridItem() {
            Text(item)
              .fontSize(16)
              .backgroundColor(0xF9CF93)
              .width(60)
              .height(60)
              .textAlign(TextAlign.Center)
          }
        })
      }
      .columnsGap(10)
      .rowsGap(10)
      .width(this.gridWidth)
      .backgroundColor(0xFAEEE0)
      .height(this.gridHeight)
      .layoutDirection(GridDirection.Row)
      .maxCount(4)
      .minCount(2)
      Text('动态行列')
    }.width('100%').height('100%')
  }
}

####需要注意: 1.当Grid组件设置了rowsTemplate或columnsTemplate时,Grid的layoutDirection、maxCount、minCount、cellLength属性不生效 2.layoutDirection不能和rowsTemplate或columnsTemplate同时使用,不生效 仅设置rowsTemplate时,Grid主轴为水平方向,交叉轴为垂直方向。 仅设置columnsTemplate时,Grid主轴为垂直方向,交叉轴为水平方向。 3.只要设置rowsTemplate属性的值且不设置columnsTemplate属性,当内容超出Grid组件宽度时,Grid可横向滚动进行内容展示

收藏00

登录 后评论。没有帐号? 注册 一个。