写点什么

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

作者:auhgnixgnahz
  • 2025-06-23
    北京
  • 本文字数:1255 字

    阅读完需:约 4 分钟

网格布局是由“行”和“列”分割的单元格所组成,通过指定“项目”所在的单元格做出各种各样的布局。网格布局具有较强的页面均分能力,子组件占比控制能力,是一种重要自适应布局,其使用场景有九宫格图片展示、日历、计算器等。


以下通过两种创建网格的方式演示:


1.固定行列分割比例,这种方式,可以让网格子布局按比例充满


2.通过设置最大行/列,最小列/行限制子布局,这样可以根据屏幕的宽高,动态的展示



@Entry@ComponentV2struct 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 可横向滚动进行内容展示


发布于: 刚刚阅读数: 4
用户头像

auhgnixgnahz

关注

还未添加个人签名 2018-07-10 加入

还未添加个人简介

评论

发布
暂无评论
鸿蒙Next网格布局Grid简单使用_鸿蒙Next_auhgnixgnahz_InfoQ写作社区