鸿蒙~ArkUI 基础 Grid网格布局

2023-12-26  本文已影响0人  胡修波

一、设置排列方式

rowsTemplate和columnsTemplate属性值是一个由多个空格和'数字+fr'间隔拼接的字符串,fr的个数即网格布局的行或列数,fr前面的数值大小,用于计算该行或列在网格布局宽度上的占比,最终决定该行或列的宽度

@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  build() {
    Grid() {
      GridItem() {
        Text("1")
      }.backgroundColor(Color.Black)

      GridItem() {
        Text("2")
      }.backgroundColor(Color.Blue)

      GridItem() {
        Text("3")
      }.backgroundColor(Color.Brown)

      GridItem() {
        Text("4")
      }.backgroundColor(Color.Green)

      GridItem() {
        Text("5")
      }.backgroundColor(Color.Grey)

      GridItem() {
        Text("6")
      }.backgroundColor(Color.Orange)

      GridItem() {
        Text("7")
      }.backgroundColor(Color.Pink)

      GridItem() {
        Text("8")
      }.backgroundColor(Color.Red)

      GridItem() {
        Text("9")
      }.backgroundColor(Color.Yellow)
    }
    .rowsTemplate('1fr 2fr 2fr')
    .columnsTemplate('1fr 2fr 1fr')
  }
}
微信图片_20231226093638.png
@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  build() {
    Grid() {
      GridItem() {
        Text("1")
      }
      .backgroundColor(Color.Black)
      .columnStart(1)
      .columnEnd(3)

      GridItem() {
        Text("2")
      }.backgroundColor(Color.Blue)

      GridItem() {
        Text("3")
      }.backgroundColor(Color.Brown)

      GridItem() {
        Text("4")
      }.backgroundColor(Color.Green)


      GridItem() {
        Text("5")
      }.backgroundColor(Color.Grey)

      GridItem() {
        Text("6")
      }.backgroundColor(Color.Orange)

      GridItem() {
        Text("7")
      }.backgroundColor(Color.Pink)

      GridItem() {
        Text("8")
      }.backgroundColor(Color.Red)

      GridItem() {
        Text("9")
      }.backgroundColor(Color.Yellow)
    }
    .rowsTemplate('1fr 2fr 2fr')
    .columnsTemplate('1fr 2fr 1fr')
  }
}
微信图片_20231226101616.png
  1. layoutDirection属性仅在不设置rowsTemplate和columnsTemplate时生效,此时元素在layoutDirection方向上排列。

  2. 仅设置rowsTemplate时,Grid主轴为水平方向,交叉轴为垂直方向。

  3. 仅设置columnsTemplate时,Grid主轴为垂直方向,交叉轴为水平方向。

上一篇 下一篇

猜你喜欢

热点阅读