【鸿蒙应用】Grid和GridItem组件
Grid是网格容器,有行和列组成,通过GridItem组件所在的单元格做出各种各样的布局。比如:
@Entry
@Preview
@Component
struct Index {private arr: string[] = ["1", "2", "31", "14", "51", "61", "71", "18"];build() {Column() {Grid() {ForEach(this.arr, (day: string) => {GridItem() {Text(day).fontSize(16).backgroundColor(0xF9CF93).width("100%").height("100%").textAlign(TextAlign.Center)}}, (day: string) => day)}.columnsTemplate("1fr 1fr 1fr 1fr 1fr").rowsTemplate("1fr 1fr 1fr 1fr 1fr").columnsGap(10).rowsGap(10).width("90%").backgroundColor(0xFAEEE0)}.height('100%').width('100%')}
}
通过columnsTemplate来设置当前网格布局列的数量,默认是 1 列。上面的代码效果如下图所示:
rowsTemplate属性,则是用来设置当前网格布局行的数量。
GridRow和GridCol
GridRow和GridCol只能在栅格布局场景中使用,GridRow常用的几个属性:
- gutter:栅格布局的间距,x:表示水平方向
- columns:设置布局列数
- breakpoints:设置断点值的断点数列以及基于窗口或者容器尺寸的相应参照
- direction:栅格布局的方向
实例代码:
@Entry
@Preview
@Component
struct Index {private bgColors: Color[] =[Color.Red, Color.Orange, Color.Black, Color.Yellow, Color.Green, Color.Pink, Color.Gray, Color.Blue, Color.Brown];build() {Column() {GridRow({columns: 5, // 设置布局列数gutter: { x: 5, y: 20 }, // 栅格布局的间距breakpoints: {value: ["400vp", "600vp", "800vp"],reference: BreakpointsReference.WindowSize},}) {ForEach(this.bgColors, (color:string) => {GridCol({ span: { xs: 1,sm:2,md:3,lg:4 } }){Row().width("100%").height("80vp")}.backgroundColor(color).borderWidth(2)})}}.height('100%').width('100%')}
}
这就是网格布局的相关组件