• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Grid
2
3The **\<Grid>** component consists of cells formed by rows and columns. You can specify the cells where items are located to form various layouts.
4
5>  **NOTE**
6>
7>  This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
8
9
10## Child Components
11
12The **\<Grid>** component accepts only **\<[GridItem](ts-container-griditem.md)>** as its child components.
13
14>  **NOTE**
15>
16>  Below are the rules for calculating the indexes of the child components of **\<Grid>**:
17>
18>  The index increases in ascending order of child components.
19>
20>  In the **if/else** statement, only the child components in the branch where the condition is met participate in the index calculation.
21>
22>  In the **ForEach** or **LazyForEach** statement, the indexes of all expanded subnodes are calculated.
23>
24>  If the values of [if/else](../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md) change, the indexes of subnodes are updated.
25>
26>  The child component that has the **visibility** attribute set to **Hidden** or **None** is included in the index calculation.
27>
28>  The child component that has the **visibility** attribute set to **None** is not displayed, but still takes up the corresponding cell.
29>
30>  The child component that has the **position** attribute set takes up the corresponding cell, and is offset by the distance specified by **position** relative to the upper left corner of the grid. This child component does not scroll with the corresponding cell and is not displayed after the corresponding cell extends beyond the display range of the grid.
31
32## APIs
33
34Grid(scroller?: Scroller)
35
36**Parameters**
37
38| Name  | Type                                   | Mandatory| Description                                                    |
39| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ |
40| scroller | [Scroller](ts-container-scroll.md#scroller) | No  | Controller, which can be bound to scrollable components.<br>**NOTE**<br>The scroller cannot be bound to other [scrollable components](ts-container-list.md).|
41
42## Attributes
43
44In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
45
46| Name| Type| Description|
47| -------- | -------- | -------- |
48| columnsTemplate | string | Number of columns in the current grid layout. If this attribute is not set, one column will be used.<br>For example, **'1fr 1fr 2fr'** indicates three columns, with the first column taking up 1/4 of the parent component's full width, the second column 1/4, and the third column 2/4.<br>**NOTE**<br>If this attribute is set to **'0fr'**, the column width is 0, and grid item in the column is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one column.|
49| rowsTemplate | string | Number of rows in the current grid layout. If this attribute is not set, one row will be used.<br>For example, **'1fr 1fr 2fr'** indicates three rows, with the first row taking up 1/4 of the parent component's full height, the second row 1/4, and the third row 2/4.<br>**NOTE**<br>If this attribute is set to **'0fr'**, the row width is 0, and grid item in the row is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one row.|
50| columnsGap | [Length](ts-types.md#length) | Gap between columns.<br>Default value: **0**<br>**NOTE**<br>A value less than 0 evaluates to the default value.|
51| rowsGap | [Length](ts-types.md#length) | Gap between rows.<br>Default value: **0**<br>**NOTE**<br>A value less than 0 evaluates to the default value.|
52| scrollBar      | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Off** |
53| scrollBarColor | string \| number \| [Color](ts-appendix-enums.md#color) | Color of the scrollbar.|
54| scrollBarWidth | string \| number    | Width of the scrollbar. After the width is set, the scrollbar is displayed with the set width in normal state and pressed state.<br>Default value: **4**<br>Unit: vp|
55| cachedCount | number                                   | Number of grid items to be preloaded (cached). It works only in [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md). For details, see [Minimizing White Blocks During Swiping](../../ui/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).<br>Default value: **1**<br>**NOTE**<br>The number of the grid items to be cached before and after the currently displayed one equals the value of **cachedCount** multiplied by the number of columns.<br>Grid items that exceed the display and cache range are released.<br>A value less than 0 evaluates to the default value.|
56| editMode <sup>8+</sup>                   | boolean | Whether to enter editing mode. In editing mode, the user can drag the **\<[GridItem](ts-container-griditem.md)>** in the **\<Grid>** component.<br>Default value: **false**|
57| layoutDirection<sup>8+</sup>             | [GridDirection](#griddirection8) | Main axis direction of the grid.<br>Default value: **GridDirection.Row**|
58| maxCount<sup>8+</sup> | number  | When **layoutDirection** is **Row** or **RowReverse**: maximum number of columns that can be displayed.<br>When **layoutDirection** is **Column** or **ColumnReverse**: maximum number of rows that can be displayed.<br>Default value: **Infinity**<br>**NOTE**<br>If the value of **maxCount** is smaller than that of **minCount**, the default values of **maxCount** and **minCount** are used.<br>A value less than 0 evaluates to the default value.|
59| minCount<sup>8+</sup> | number  | When **layoutDirection** is **Row** or **RowReverse**: minimum number of columns that can be displayed.<br>When **layoutDirection** is **Column** or **ColumnReverse**: minimum number of rows that can be displayed.<br>Default value: **1**<br>**NOTE**<br>A value less than 0 evaluates to the default value.|
60| cellLength<sup>8+</sup> | number  | When **layoutDirection** is **Row** or **RowReverse**: fixed height per row.<br>When **layoutDirection** is **Column** or **ColumnReverse**: fixed width per column.<br>Default value: size of the first element|
61| multiSelectable<sup>8+</sup> | boolean | Whether to enable mouse frame selection.<br>Default value: **false**<br>- **false**: The mouse frame selection is disabled.<br>- **true**: The mouse frame selection is enabled.|
62| supportAnimation<sup>8+</sup> | boolean | Whether to enable animation. Currently, the grid item drag animation is supported.<br>Default value: **false**|
63
64Depending on the settings of the **rowsTemplate** and **columnsTemplate** attributes, the **\<Grid>** component supports the following layout modes:
65
661. **rowsTemplate** and **columnsTemplate** are both set
67
68- The **\<Grid>** component displays only elements in a fixed number of rows and columns and cannot be scrolled.
69- In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, **minCount**, and **cellLength**.
70- If the width and height of a grid are not set, the grid adapts to the size of its parent component by default.
71- The size of the grid rows and columns is the size of the grid content area minus the gap between rows and columns. It is allocated based on the proportion of each row and column.
72- By default, the grid items fill the entire grid.
73
742. Either **rowsTemplate** or **columnsTemplate** is set
75
76- The **\<Grid>** component arranges elements in the specified direction and allows for scrolling to display excess elements.
77- If **columnsTemplate** is set, the component scrolls vertically, the main axis runs vertically, and the cross axis runs horizontally.
78- If **rowsTemplate** is set, the component scrolls horizontally, the main axis runs horizontally, and the cross axis runs vertically.
79- In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, minCount, and **cellLength**.
80- The cross axis size of the grid is the cross axis size of the grid content area minus the gaps along the cross axis. It is allocated based on the proportion of each row and column.
81- The main axis size of the grid is the maximum height of all grid items in the cross axis direction of the current grid.
82
833. Neither **rowsTemplate** nor **columnsTemplate** is set
84
85- The **\<Grid>** component arranges elements in the direction specified by **layoutDirection**. The number of columns is jointly determined by the grid width, width of the first element, **minCount**, **maxCount**, and **columnsGap**.
86- The number of rows is jointly determined by the grid height, height of the first element, **cellLength**, and **rowsGap**. Elements outside the determined range of rows and columns are not displayed and cannot be viewed through scrolling.
87- In this mode, only the following attributes take effect: **layoutDirection**, **maxCount**, **minCount**, **cellLength**, **editMode**, **columnsGap**, and **rowsGap**.
88- When **layoutDirection** is set to **Row**, elements are arranged row by row from left to right. If the remaining height is insufficient, no more elements will be laid out, and the whole content is centered at the top.
89- When **layoutDirection** is set to **Column**, elements are arranged column by column from top to bottom. If the remaining height is insufficient, no more elements will be laid out, and the whole content is centered at the top.
90
91## GridDirection<sup>8+</sup>
92
93| Name  | Description                                  |
94| ------ | -------------------------------------- |
95| Row  | Horizontal layout, where the child components are arranged from left to right as the main axis runs along the rows.|
96| Column | Vertical layout, where the child components are arranged from top to bottom as the main axis runs down the columns.|
97| RowReverse    | Reverse horizontal layout, where the child components are arranged from right to left as the main axis runs along the rows.|
98| ColumnReverse   | Reverse vertical layout, where the child components are arranged from bottom up as the main axis runs down the columns.|
99
100> **NOTE**
101>
102> The default value of the universal attribute [clip](ts-universal-attributes-sharp-clipping.md) is **true** for the **\<Grid>** component.
103
104## Events
105
106In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
107
108| Name| Description|
109| -------- | -------- |
110| onScrollIndex(event: (first: number) => void) | Triggered when the first item displayed in the grid changes. It is triggered once when the grid is initialized.<br>- **first**: index of the first item of the grid.<br>If it changes, this event will be triggered.|
111| onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => (() => any) \| void) | Triggered when a grid item starts to be dragged.<br>- **event**: See [ItemDragInfo](#itemdraginfo).<br>- **itemIndex**: index of the dragged item.<br>**NOTE**<br>If **void** is returned, the drag operation cannot be performed.<br>This event is triggered when the user long presses a grid item.|
112| onItemDragEnter(event: (event: ItemDragInfo) => void) | Triggered when the dragged item enters the drop target of the grid.<br>- **event**: See [ItemDragInfo](#itemdraginfo).|
113| onItemDragMove(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number) => void) | Triggered when the dragged item moves over the drop target of the grid.<br>- **event**: See [ItemDragInfo](#itemdraginfo).<br>- **itemIndex**: initial position of the dragged item.<br>- **insertIndex**: index of the position to which the dragged item will be dropped.|
114| onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | Triggered when the dragged item leaves the drop target of the grid.<br>- **event**: See [ItemDragInfo](#itemdraginfo).<br>- **itemIndex**: index of the dragged item.|
115| onItemDrop(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => void) | Triggered when the dragged item is dropped on the drop target of the grid.<br>- **event**: See [ItemDragInfo](#itemdraginfo).<br>- **itemIndex**: initial position of the dragged item.<br>- **insertIndex**: index of the position to which the dragged item will be dropped.<br>- **isSuccess**: whether the dragged item is successfully dropped.|
116
117## ItemDragInfo
118
119| Name        | Type        |   Description        |
120| ---------- | ---------- | ---------- |
121| x | number |  X coordinate of the dragged item.   |
122| y   | number |  Y coordinate of the dragged item.   |
123
124## Example
125
126```ts
127// xxx.ets
128@Entry
129@Component
130struct GridExample {
131  @State Number: String[] = ['0', '1', '2', '3', '4']
132  scroller: Scroller = new Scroller()
133
134  build() {
135    Column({ space: 5 }) {
136      Grid() {
137        ForEach(this.Number, (day: string) => {
138          ForEach(this.Number, (day: string) => {
139            GridItem() {
140              Text(day)
141                .fontSize(16)
142                .backgroundColor(0xF9CF93)
143                .width('100%')
144                .height('100%')
145                .textAlign(TextAlign.Center)
146            }
147          }, day => day)
148        }, day => day)
149      }
150      .columnsTemplate('1fr 1fr 1fr 1fr 1fr')
151      .rowsTemplate('1fr 1fr 1fr 1fr 1fr')
152      .columnsGap(10)
153      .rowsGap(10)
154      .width('90%')
155      .backgroundColor(0xFAEEE0)
156      .height(300)
157
158      Text('scroll').fontColor(0xCCCCCC).fontSize(9).width('90%')
159      Grid(this.scroller) {
160        ForEach(this.Number, (day: string) => {
161          ForEach(this.Number, (day: string) => {
162            GridItem() {
163              Text(day)
164                .fontSize(16)
165                .backgroundColor(0xF9CF93)
166                .width('100%')
167                .height(80)
168                .textAlign(TextAlign.Center)
169            }
170          }, day => day)
171        }, day => day)
172      }
173      .columnsTemplate('1fr 1fr 1fr 1fr 1fr')
174      .columnsGap(10)
175      .rowsGap(10)
176      .onScrollIndex((first: number) => {
177        console.info(first.toString())
178      })
179      .width('90%')
180      .backgroundColor(0xFAEEE0)
181      .height(300)
182      Button('next page')
183        .onClick(() => {// Click to go to the next page.
184          this.scroller.scrollPage({ next: true })
185        })
186    }.width('100%').margin({ top: 5 })
187  }
188}
189```
190
191![en-us_image_0000001219744183](figures/en-us_image_0000001219744183.gif)
192