• 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>  Child components of **\<Grid>** whose **visibility** attribute is set to **Hidden** or **None** are included in the index calculation.
27>
28>  Child components of **\<Grid>** whose **visibility** attribute is set to **None** are not displayed, but still take up the corresponding cells.
29
30
31## APIs
32
33Grid(scroller?: Scroller)
34
35**Parameters**
36
37| Name  | Type                                   | Mandatory| Description                                                    |
38| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ |
39| 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).|
40
41## Attributes
42
43In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
44
45| Name| Type| Description|
46| -------- | -------- | -------- |
47| columnsTemplate | string | Number of columns in the current grid layout. If this attribute is not set, one column is used by default.<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.|
48| rowsTemplate | string | Number of rows in the current grid layout. If this attribute is not set, one row is used by default.<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.|
49| 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.|
50| 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.|
51| scrollBar      | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Off** |
52| scrollBarColor | string \| number \| [Color](ts-appendix-enums.md#color) | Color of the scrollbar.|
53| 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|
54| 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.|
55| 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**|
56| layoutDirection<sup>8+</sup>             | [GridDirection](#griddirection8) | Main axis direction of the grid.<br>Default value: **GridDirection.Row**|
57| 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.|
58| 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.|
59| 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|
60| 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.|
61| supportAnimation<sup>8+</sup> | boolean | Whether to enable animation. Currently, the grid item drag animation is supported.<br>Default value: **false**|
62
63Depending on the settings of the **rowsTemplate** and **columnsTemplate** attributes, the **\<Grid>** component supports the following layout modes:
64
651. **rowsTemplate** and **columnsTemplate** are both set
66
67- The **\<Grid>** component displays only elements in a fixed number of rows and columns and cannot be scrolled.
68- In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, **minCount**, and **cellLength**.
69- If the width and height of a grid are not set, the grid adapts to the size of its parent component by default.
70- 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.
71- By default, the grid items fill the entire grid.
72- In this mode, if a grid item has both **rowStart** and **columnStart** set, it is placed in the position based on the settings. If a grid item already exists in this position, overlapping occurs.
73- If a grid item has only **rowStart** or **columnStart** set, the system traverses the previous grid item layout to search for an idle position that meets the settings. If no idle position meets the requirements, the grid item is not laid out.
74- If a grid item has neither **rowStart** nor **columnStart** set, the system traverses the previous grid item layout to search for an idle position. If no idle position is available, the grid item is not laid out.
75- If a grid item has **rowEnd** set but not **rowStart**, **rowStart** is considered as set to the same value as **rowEnd**. If a grid item has **columnEnd** set but not **columnStart**, **columnStart** is considered as set to the same value as **columnEnd**.
76
772. Either **rowsTemplate** or **columnsTemplate** is set
78
79- The **\<Grid>** component arranges elements in the specified direction and allows for scrolling to display excess elements.
80- If **columnsTemplate** is set, the component scrolls vertically, the main axis runs vertically, and the cross axis runs horizontally.
81- If **rowsTemplate** is set, the component scrolls horizontally, the main axis runs horizontally, and the cross axis runs vertically.
82- In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, minCount, and **cellLength**.
83- 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.
84- The main axis size of the grid is the maximum height of all grid items in the cross axis direction of the current grid.
85- In this mode, if a grid item has both **rowStart** and **columnStart** set, it is placed in the position based on the settings. If a grid item already exists in this position, overlapping occurs.
86- If a grid item has only **rowStart** or **columnStart** set, the system traverses the previous grid item layout to search for an idle position that meets the settings.
87- If a grid item has neither **rowStart** nor **columnStart** set, the system traverses the previous grid item layout to search for an idle position.
88- If a grid item has **rowEnd** set but not **rowStart**, **rowStart** is considered as set to the same value as **rowEnd**. If a grid item has **columnEnd** set but not **columnStart**, **columnStart** is considered as set to the same value as **columnEnd**.
89
903. Neither **rowsTemplate** nor **columnsTemplate** is set
91
92- 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**.
93- 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.
94- In this mode, only the following attributes take effect: **layoutDirection**, **maxCount**, **minCount**, **cellLength**, **editMode**, **columnsGap**, and **rowsGap**.
95- When **layoutDirection** is set to **Row**, elements are arranged from left to right. When a row is full, a new row will be added. If the remaining height is insufficient, no more elements will be laid out, and the top of the content is centered.
96- When **layoutDirection** is set to **Column**, elements are arranged from top to bottom. When a column is full, a new column will be added. If the remaining height is insufficient, no more elements will be laid out, and the top of the content is centered.
97- In this mode, **rowStart** and **columnStart** of the grid item do not take effect.
98
99## GridDirection<sup>8+</sup>
100
101| Name  | Description                                  |
102| ------ | -------------------------------------- |
103| Row  | Horizontal layout, where the child components are arranged from left to right as the main axis runs along the rows.|
104| Column | Vertical layout, where the child components are arranged from top to bottom as the main axis runs down the columns.|
105| RowReverse    | Reverse horizontal layout, where the child components are arranged from right to left as the main axis runs along the rows.|
106| ColumnReverse   | Reverse vertical layout, where the child components are arranged from bottom up as the main axis runs down the columns.|
107
108> **NOTE**
109>
110> The default value of the universal attribute [clip](ts-universal-attributes-sharp-clipping.md) is **true** for the **\<Grid>** component.
111
112## Events
113
114In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
115
116| Name| Description|
117| -------- | -------- |
118| onScrollIndex(event: (first: number) => void) | Triggered when the start item of the grid changes. It is triggered once when the grid is initialized.<br>- **first**: index of the start item of the grid.<br>If it changes, this event will be triggered.|
119| 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 element.<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.|
120| onItemDragEnter(event: (event: ItemDragInfo) => void) | Triggered when the dragged item enters the drop target of the grid.<br>- **event**: See [ItemDragInfo](#itemdraginfo).|
121| 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.|
122| onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | Triggered when the dragged item exits the drop target of the grid.<br>- **event**: See [ItemDragInfo](#itemdraginfo).<br>- **itemIndex**: index of the dragged item.|
123| 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.|
124
125## ItemDragInfo
126
127| Name        | Type        |   Description        |
128| ---------- | ---------- | ---------- |
129| x | number |  X coordinate of the dragged item.   |
130| y   | number |  Y coordinate of the dragged item.   |
131
132## Example
133
134```ts
135// xxx.ets
136@Entry
137@Component
138struct GridExample {
139  @State Number: String[] = ['0', '1', '2', '3', '4']
140  scroller: Scroller = new Scroller()
141
142  build() {
143    Column({ space: 5 }) {
144      Grid() {
145        ForEach(this.Number, (day: string) => {
146          ForEach(this.Number, (day: string) => {
147            GridItem() {
148              Text(day)
149                .fontSize(16)
150                .backgroundColor(0xF9CF93)
151                .width('100%')
152                .height('100%')
153                .textAlign(TextAlign.Center)
154            }
155          }, day => day)
156        }, day => day)
157      }
158      .columnsTemplate('1fr 1fr 1fr 1fr 1fr')
159      .rowsTemplate('1fr 1fr 1fr 1fr 1fr')
160      .columnsGap(10)
161      .rowsGap(10)
162      .width('90%')
163      .backgroundColor(0xFAEEE0)
164      .height(300)
165
166      Text('scroll').fontColor(0xCCCCCC).fontSize(9).width('90%')
167      Grid(this.scroller) {
168        ForEach(this.Number, (day: string) => {
169          ForEach(this.Number, (day: string) => {
170            GridItem() {
171              Text(day)
172                .fontSize(16)
173                .backgroundColor(0xF9CF93)
174                .width('100%')
175                .height(80)
176                .textAlign(TextAlign.Center)
177            }
178          }, day => day)
179        }, day => day)
180      }
181      .columnsTemplate('1fr 1fr 1fr 1fr 1fr')
182      .columnsGap(10)
183      .rowsGap(10)
184      .onScrollIndex((first: number) => {
185        console.info(first.toString())
186      })
187      .width('90%')
188      .backgroundColor(0xFAEEE0)
189      .height(300)
190      Button('next page')
191        .onClick(() => {// Click to go to the next page.
192          this.scroller.scrollPage({ next: true })
193        })
194    }.width('100%').margin({ top: 5 })
195  }
196}
197```
198
199![en-us_image_0000001219744183](figures/en-us_image_0000001219744183.gif)
200