• 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
12Only the [GridItem](ts-container-griditem.md) child component is allowed, with support for [if/else](../../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../../quick-start/arkts-rendering-control-foreach.md), [LazyForEach](../../../quick-start/arkts-rendering-control-lazyforeach.md), and [Repeat](../../../quick-start/arkts-new-rendering-control-repeat.md) rendering control.
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**, **LazyForEach**, or **Repeat** statement, the indexes of all expanded child nodes are calculated.
23>
24>  After changes occur in [if/else](../../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../../quick-start/arkts-rendering-control-foreach.md), [LazyForEach](../../../quick-start/arkts-rendering-control-lazyforeach.md), or [Repeat](../../../quick-start/arkts-new-rendering-control-repeat.md), the indexes of the child nodes 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 is displayed in the corresponding cell, 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>  When there is a gap between child components, it is filled as much as possible based on the current display area. Therefore, the relative position of grid items may change as the grid scrolls.
33
34## APIs
35
36Grid(scroller?: Scroller, layoutOptions?: GridLayoutOptions)
37
38Creates a **Grid** component.
39
40**Atomic service API**: This API can be used in atomic services since API version 11.
41
42**System capability**: SystemCapability.ArkUI.ArkUI.Full
43
44**Parameters**
45
46| Name  | Type                                   | Mandatory| Description                                                    |
47| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ |
48| 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, such as [List](ts-container-list.md), [Grid](ts-container-grid.md), or [Scroll](ts-container-scroll.md).|
49| layoutOptions<sup>10+</sup> | [GridLayoutOptions](#gridlayoutoptions10) | No| Grid layout options.|
50
51## GridLayoutOptions<sup>10+</sup>
52
53Defines the grid layout options. In this API, **irregularIndexes** and **onGetIrregularSizeByIndex** can be used for grids where either **rowsTemplate** or **columnsTemplate** is set. These properties allow you to specify an index array and set the number of rows and columns to be occupied by a grid item at the specified index. For details about the usage, see [Example 3](#example-3-implementing-a-scrollable-grid-with-grid-items-spanning-rows-and-columns). On the other hand, **onGetRectByIndex** can be used for grids where both **rowsTemplate** and **columnsTemplate** are set. It allows you to specify the position and size for the grid item at the specified index. For details about the usage, see [Example 1](#example-1-creating-a-fixed-row-and-column-grid-layout).
54
55**System capability**: SystemCapability.ArkUI.ArkUI.Full
56
57| Name   | Type     | Mandatory  | Description                   |
58| ----- | ------- | ---- | --------------------- |
59| regularSize  | [number, number]  | Yes   | Number of rows and columns occupied by a grid item with regular size. The only supported value is **[1, 1]**, meaning that the grid item occupies one row and one column.<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
60| irregularIndexes | number[] | No   | Indexes of the grid item with an irregular size in the grid. When **onGetIrregularSizeByIndex** is not set, the grid item specified in this parameter occupies an entire row of the grid that scrolls vertically or an entire column of the grid that scrolls horizontally.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
61| onGetIrregularSizeByIndex | (index: number) => [number, number] | No   | Number of rows and columns occupied by the grid item with an irregular size. This parameter is used together with **irregularIndexes**. In versions earlier than API version 12, the vertical scrolling grid does not support grid items spanning multiple rows, and the horizontal scrolling grid does not support grid items spanning multiple columns.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
62| onGetRectByIndex<sup>11+</sup> | (index: number) => [number, number,number,number] | No | Position and size of the grid item with the specified index, in the format of [rowStart,columnStart,rowSpan,columnSpan],<br>where **rowStart** indicates the row start position, **columnStart** indicates the column start position,<br>**rowSpan** indicates the number of rows occupied by the grid item, and **columnSpan** indicates the number of columns occupied by the grid item. Their values are unitless.<br>The values of **rowStart** and **columnStart** are natural numbers greater than or equal to 0. If a negative value is set, the default value **0** is used.<br>The values of **rowSpan** and **columnSpan** are natural numbers greater than or equal to 1. If a decimal is set, it is rounded down. If the decimal set is less than 1, the value **1** is used.<br>**NOTE**<br>Case 1: If a grid item finds that the start position specified for it is already occupied, it searches for an available start position from left to right and from top to bottom, starting from position [0,0].<br>Case 2: If any space other than the start position specified for a grid item is occupied, the grid item is displayed within the available space left.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
63
64## Attributes
65
66In addition to [universal attributes](ts-component-general-attributes.md) and [scrollable component common attributes](ts-container-scrollable-common.md#attributes), the following attributes are also supported.
67
68### columnsTemplate
69
70columnsTemplate(value: string)
71
72Sets the number of columns, fixed column width, or minimum column width of the grid. If this attribute is not set, one column will be used.
73
74For 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.
75
76**columnsTemplate('repeat(auto-fit, track-size)')**: The layout automatically calculates the number of columns and the actual column width, while adhering to the minimum column width specified with **track-size**.
77
78**columnsTemplate('repeat(auto-fill, track-size)')**: The layout automatically calculates the number of columns based on the fixed column width specified with **track-size**.
79
80**columnsTemplate('repeat(auto-stretch, track-size)')**: The layout uses **columnsGap** to define the minimum gap between columns and automatically calculates the number of columns and the actual gap size based on the fixed column width specified with **track-size**.
81
82**repeat**, **auto-fit**, **auto-fill**, and **auto-stretch** are keywords. **track-size** indicates the column width, in the unit of px, vp (default), %, or any valid digit. The value must be greater than or equal to one valid column width.<br>
83In **auto-stretch** mode, **track-size** must be a valid column width value, in the unit of px, vp, or any valid digit; percentage values (%) are not supported.
84
85For details about the effect, see [Example 8](#example-8-using-adaptive-column-count-settings).
86
87If 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.
88
89**Atomic service API**: This API can be used in atomic services since API version 11.
90
91**System capability**: SystemCapability.ArkUI.ArkUI.Full
92
93**Parameters**
94
95| Name| Type  | Mandatory| Description                              |
96| ------ | ------ | ---- | ---------------------------------- |
97| value  | string | Yes  | Number of columns or minimum column width of the grid.|
98
99### rowsTemplate
100
101rowsTemplate(value: string)
102
103Sets the number of rows, fixed row height, or minimum row height of the grid. If this attribute is not set, one row will be used.
104
105For 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.
106
107**rowsTemplate('repeat(auto-fit, track-size)')**: The layout automatically calculates the number of rows and the actual row height, while adhering to the minimum row height specified with **track-size**.
108
109**rowsTemplate('repeat(auto-fill, track-size)')**: The layout automatically calculates the number of rows based on the fixed row height specified with **track-size**.
110
111**rowsTemplate('repeat(auto-stretch, track-size)')**: The layout uses **rowsGap** to define the minimum gap between rows and automatically calculates the number of rows and the actual gap size based on the fixed row height specified with **track-size**.
112
113**repeat**, **auto-fit**, **auto-fill**, and **auto-stretch** are keywords. **track-size** indicates the row height, in the unit of px, vp (default), %, or any valid digit. The value must be greater than or equal to one valid row height.<br>
114In **auto-stretch** mode, **track-size** must be a valid row height value, in the unit of px, vp, or any valid digit; percentage values (%) are not supported.
115
116If 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.
117
118**Atomic service API**: This API can be used in atomic services since API version 11.
119
120**System capability**: SystemCapability.ArkUI.ArkUI.Full
121
122**Parameters**
123
124| Name| Type  | Mandatory| Description                              |
125| ------ | ------ | ---- | ---------------------------------- |
126| value  | string | Yes  | Number of rows or minimum row height of the grid.|
127
128>  **NOTE**
129>
130>  Depending on the settings of the **rowsTemplate** and **columnsTemplate** attributes, the **Grid** component supports the following layout modes:
131>
132>  1. **rowsTemplate** and **columnsTemplate** are both set
133>
134>  - The **Grid** component displays only elements in a fixed number of rows and columns and cannot be scrolled.
135>  - In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, **minCount**, and **cellLength**.
136>  - If the width and height of a grid are not set, the grid adapts to the size of its parent component by default.
137>  - 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.
138>  - By default, the grid items fill the entire grid.
139>
140>  2. Either **rowsTemplate** or **columnsTemplate** is set
141>
142>  - The **Grid** component arranges elements in the specified direction and allows for scrolling to display excess elements.
143>  - If **columnsTemplate** is set, the component scrolls vertically, the main axis runs vertically, and the cross axis runs horizontally.
144>  - If **rowsTemplate** is set, the component scrolls horizontally, the main axis runs horizontally, and the cross axis runs vertically.
145>  - In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, **minCount**, and **cellLength**.
146>  - 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.
147>  - The main axis size of the grid is the maximum value of the main axis sizes of all grid items in the cross axis direction of the grid.
148>
149>  3. Neither **rowsTemplate** nor **columnsTemplate** is set
150>
151>  - 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**.
152>  - 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.
153>  - In this mode, only the following attributes take effect: **layoutDirection**, **maxCount**, **minCount**, **cellLength**, **editMode**, **columnsGap**, and **rowsGap**.
154>  - When **layoutDirection** is set to **Row**, child components 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 whole content is centered at the top.
155>  - 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.
156>  - If there are no grid items in the grid, the width and height of the grid are set to 0.
157>
158
159### columnsGap
160
161columnsGap(value: Length)
162
163Sets the gap between columns. A value less than 0 evaluates to the default value.
164
165**Atomic service API**: This API can be used in atomic services since API version 11.
166
167**System capability**: SystemCapability.ArkUI.ArkUI.Full
168
169**Parameters**
170
171| Name| Type                        | Mandatory| Description                        |
172| ------ | ---------------------------- | ---- | ---------------------------- |
173| value  | [Length](ts-types.md#length) | Yes  | Gap between columns.<br>Default value: **0**|
174
175### rowsGap
176
177rowsGap(value: Length)
178
179Sets the gap between rows. A value less than 0 evaluates to the default value.
180
181**Atomic service API**: This API can be used in atomic services since API version 11.
182
183**System capability**: SystemCapability.ArkUI.ArkUI.Full
184
185**Parameters**
186
187| Name| Type                        | Mandatory| Description                        |
188| ------ | ---------------------------- | ---- | ---------------------------- |
189| value  | [Length](ts-types.md#length) | Yes  | Gap between rows.<br>Default value: **0**|
190
191### scrollBar
192
193scrollBar(value: BarState)
194
195Sets the scrollbar state.
196
197**Atomic service API**: This API can be used in atomic services since API version 11.
198
199**System capability**: SystemCapability.ArkUI.ArkUI.Full
200
201**Parameters**
202
203| Name| Type                                     | Mandatory| Description                                                        |
204| ------ | ----------------------------------------- | ---- | ------------------------------------------------------------ |
205| value  | [BarState](ts-appendix-enums.md#barstate) | Yes  | Scrollbar state.<br>Default value: **BarState.Auto**<br>**NOTE**<br>In API version 9 and earlier versions, the default value is **BarState.Off**. Since API version 10, the default value is **BarState.Auto**.|
206
207### scrollBarColor
208
209scrollBarColor(value: Color | number | string)
210
211Sets the scrollbar color.
212
213**Atomic service API**: This API can be used in atomic services since API version 11.
214
215**System capability**: SystemCapability.ArkUI.ArkUI.Full
216
217**Parameters**
218
219| Name| Type                                                        | Mandatory| Description          |
220| ------ | ------------------------------------------------------------ | ---- | -------------- |
221| value  | [Color](ts-appendix-enums.md#color) \| number \| string | Yes  | Scrollbar color.<br>Default value: **'\#182431'** (40% opacity)|
222
223### scrollBarWidth
224
225scrollBarWidth(value: number | string)
226
227Sets the scrollbar width. This attribute cannot be set in percentage. After the width is set, the scrollbar is displayed with the set width in normal state and pressed state. If the set width exceeds the height of the **Grid** component on the main axis, the scrollbar reverts to the default width.
228
229**Atomic service API**: This API can be used in atomic services since API version 11.
230
231**System capability**: SystemCapability.ArkUI.ArkUI.Full
232
233**Parameters**
234
235| Name| Type                      | Mandatory| Description                                     |
236| ------ | -------------------------- | ---- | ----------------------------------------- |
237| value  | number \| string | Yes  | Scrollbar width.<br>Default value: **4**<br>Unit: vp|
238
239### cachedCount
240
241cachedCount(value: number)
242
243Sets the number of grid items to be cached (preloaded). It works only in [LazyForEach](../../../quick-start/arkts-rendering-control-lazyforeach.md) and [Repeat](../../../quick-start/arkts-new-rendering-control-repeat.md) with the **virtualScroll** option enabled. A value less than 0 evaluates to the default value. <!--Del-->For details, see [Minimizing White Blocks During Swiping](../../../performance/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).<!--DelEnd-->
244
245The 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.
246
247In [LazyForEach](../../../quick-start/arkts-rendering-control-lazyforeach.md) and [Repeat](../../../quick-start/arkts-new-rendering-control-repeat.md) with the **virtualScroll** option enabled, grid items that are outside the display and cache range will be released.
248
249**Atomic service API**: This API can be used in atomic services since API version 11.
250
251**System capability**: SystemCapability.ArkUI.ArkUI.Full
252
253**Parameters**
254
255| Name| Type  | Mandatory| Description                                                        |
256| ------ | ------ | ---- | ------------------------------------------------------------ |
257| value  | number | Yes  | Number of grid items to be cached (preloaded).<br>Default value: the number of rows visible on the screen for vertical scrolling, or the number of columns visible on the screen for horizontal scrolling. The maximum value is 16.|
258
259### cachedCount<sup>14+</sup>
260
261cachedCount(count: number, show: boolean)
262
263Sets the number of grid items to be cached (preloaded) and specifies whether to display the preloaded nodes.
264
265The 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. This attribute can be combined with the [clip](ts-universal-attributes-sharp-clipping.md#clip12) or [content clipping](ts-container-scrollable-common.md#clipcontent14) attributes to display the preloaded nodes.
266
267**Atomic service API**: This API can be used in atomic services since API version 14.
268
269**System capability**: SystemCapability.ArkUI.ArkUI.Full
270
271**Parameters**
272
273| Name| Type  | Mandatory| Description                                  |
274| ------ | ------ | ---- | -------------------------------------- |
275| count  | number | Yes  | Number of grid items to be cached (preloaded).<br>Default value: the number of rows visible on the screen for vertical scrolling, or the number of columns visible on the screen for horizontal scrolling. The maximum value is 16.|
276| show  | boolean | Yes  | Whether to display the preloaded nodes.<br> Default value: **false**|
277
278### editMode<sup>8+</sup>
279
280editMode(value: boolean)
281
282Sets whether to enable edit mode. In edit mode, the user can drag the [grid items](ts-container-griditem.md) in the **Grid** component.
283
284**Atomic service API**: This API can be used in atomic services since API version 11.
285
286**System capability**: SystemCapability.ArkUI.ArkUI.Full
287
288**Parameters**
289
290| Name| Type  | Mandatory| Description                                    |
291| ------ | ------ | ---- | ---------------------------------------- |
292| value  | boolean | Yes  | Whether to enable edit mode.<br>Default value: **false**|
293
294### layoutDirection<sup>8+</sup>
295
296layoutDirection(value: GridDirection)
297
298Sets the main axis layout direction of the grid.
299
300**Atomic service API**: This API can be used in atomic services since API version 11.
301
302**System capability**: SystemCapability.ArkUI.ArkUI.Full
303
304**Parameters**
305
306| Name| Type                                    | Mandatory| Description                                          |
307| ------ | ---------------------------------------- | ---- | ---------------------------------------------- |
308| value  | [GridDirection](#griddirection8) | Yes  | Main axis layout direction of the grid.<br>Default value: **GridDirection.Row**|
309
310### maxCount<sup>8+</sup>
311
312maxCount(value: number)
313
314Sets the maximum number of rows or columns that can be displayed. A value less than 1 evaluates to the default value.
315
316When **layoutDirection** is **Row** or **RowReverse**, the value indicates the maximum number of columns that can be displayed.
317
318When **layoutDirection** is **Column** or **ColumnReverse**, the value indicates the maximum number of rows that can be displayed.
319
320If the value of **maxCount** is smaller than that of **minCount**, the default values of **maxCount** and **minCount** are used.
321
322**Atomic service API**: This API can be used in atomic services since API version 11.
323
324**System capability**: SystemCapability.ArkUI.ArkUI.Full
325
326**Parameters**
327
328| Name| Type  | Mandatory| Description                                         |
329| ------ | ------ | ---- | --------------------------------------------- |
330| value  | number | Yes  | Maximum number of rows or columns that can be displayed.<br>Default value: **Infinity**|
331
332### minCount<sup>8+</sup>
333
334minCount(value: number)
335
336Sets the minimum number of rows or columns that can be displayed. A value less than 1 evaluates to the default value.
337
338When **layoutDirection** is **Row** or **RowReverse**, the value indicates the minimum number of columns that can be displayed.
339
340When **layoutDirection** is **Column** or **ColumnReverse**, the value indicates the minimum number of rows that can be displayed.
341
342**Atomic service API**: This API can be used in atomic services since API version 11.
343
344**System capability**: SystemCapability.ArkUI.ArkUI.Full
345
346**Parameters**
347
348| Name| Type  | Mandatory| Description                                  |
349| ------ | ------ | ---- | -------------------------------------- |
350| value  | number | Yes  | Minimum number of rows or columns that can be displayed.<br>Default value: **1**|
351
352### cellLength<sup>8+</sup>
353
354cellLength(value: number)
355
356Sets the height per row or width per column.
357
358When **layoutDirection** is **Row** or **RowReverse**, the value indicates the height per row.
359
360When **layoutDirection** is **Column** or **ColumnReverse**, the value indicates the width per column.
361
362**Atomic service API**: This API can be used in atomic services since API version 11.
363
364**System capability**: SystemCapability.ArkUI.ArkUI.Full
365
366**Parameters**
367
368| Name| Type  | Mandatory| Description                                                   |
369| ------ | ------ | ---- | ------------------------------------------------------- |
370| value  | number | Yes  | Height per row or width per column.<br>Default value: size of the first element<br>Unit: vp|
371
372### multiSelectable<sup>8+</sup>
373
374multiSelectable(value: boolean)
375
376Sets whether to enable multiselect. When multiselect is enabled, you can use the **selected** attribute and **onSelect** event to obtain the selected status of grid items; you can also set the [style](./ts-universal-attributes-polymorphic-style.md) for the selected state (by default, no style is set for the selected state).
377
378**Atomic service API**: This API can be used in atomic services since API version 11.
379
380**System capability**: SystemCapability.ArkUI.ArkUI.Full
381
382**Parameters**
383
384| Name| Type   | Mandatory| Description                                                        |
385| ------ | ------- | ---- | ------------------------------------------------------------ |
386| value  | boolean | Yes  | Whether to enable multiselect.<br>Default value: **false**<br>**false**: Multiselect is disabled. **true**: Multiselect is disabled.|
387
388### supportAnimation<sup>8+</sup>
389
390supportAnimation(value: boolean)
391
392Sets whether to enable animation. Currently, the grid item drag animation is supported. Animation is supported only in scrolling mode (only **rowsTemplate** or **columnsTemplate** is set).<br>Drag animations are only supported in grids with fixed size rules; scenarios involving spanning across rows or columns are not supported.
393
394**Atomic service API**: This API can be used in atomic services since API version 11.
395
396**System capability**: SystemCapability.ArkUI.ArkUI.Full
397
398**Parameters**
399
400| Name| Type   | Mandatory| Description                            |
401| ------ | ------- | ---- | -------------------------------- |
402| value  | boolean | Yes  | Whether to enable animation.<br>Default value: **false**|
403
404### edgeEffect<sup>10+</sup>
405
406edgeEffect(value: EdgeEffect, options?: EdgeEffectOptions)
407
408Sets the effect used when the scroll boundary is reached.
409
410**Atomic service API**: This API can be used in atomic services since API version 11.
411
412**System capability**: SystemCapability.ArkUI.ArkUI.Full
413
414**Parameters**
415
416| Name               | Type                                                        | Mandatory| Description                                                        |
417| --------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
418| value                 | [EdgeEffect](ts-appendix-enums.md#edgeeffect)                | Yes  | Effect used when the scroll boundary is reached. The spring and shadow effects are supported.<br>Default value: **EdgeEffect.None**|
419| options<sup>11+</sup> | [EdgeEffectOptions](ts-container-scrollable-common.md#edgeeffectoptions11) | No  | Whether to enable the scroll effect when the component content is smaller than the component itself. The value **{ alwaysEnabled: true }** means to enable the scroll effect, and **{ alwaysEnabled: false }** means the opposite.<br>Default value: **{ alwaysEnabled: false }**|
420
421### enableScrollInteraction<sup>10+</sup>
422
423enableScrollInteraction(value: boolean)
424
425Sets whether to support scroll gestures. When this attribute is set to **false**, scrolling by finger or mouse is not supported, but the scrolling controller API is not affected.
426
427**Atomic service API**: This API can be used in atomic services since API version 11.
428
429**System capability**: SystemCapability.ArkUI.ArkUI.Full
430
431**Parameters**
432
433| Name| Type   | Mandatory| Description                               |
434| ------ | ------- | ---- | ----------------------------------- |
435| value  | boolean | Yes  | Whether to support scroll gestures.<br>Default value: **true**|
436
437### nestedScroll<sup>10+</sup>
438
439nestedScroll(value: NestedScrollOptions)
440
441Sets the nested scrolling options. You can set the nested scrolling mode in the forward and backward directions to implement scrolling linkage with the parent component.
442
443**Atomic service API**: This API can be used in atomic services since API version 11.
444
445**System capability**: SystemCapability.ArkUI.ArkUI.Full
446
447**Parameters**
448
449| Name| Type                                                        | Mandatory| Description          |
450| ------ | ------------------------------------------------------------ | ---- | -------------- |
451| value  | [NestedScrollOptions](ts-container-scrollable-common.md#nestedscrolloptions10) | Yes  | Nested scrolling options.|
452
453### friction<sup>10+</sup>
454
455friction(value: number | Resource)
456
457Sets the friction coefficient. It applies only to gestures in the scrolling area, and it affects only indirectly the scroll chaining during the inertial scrolling process. If this attribute is set to a value less than or equal to 0, the default value is used.
458
459**Atomic service API**: This API can be used in atomic services since API version 11.
460
461**System capability**: SystemCapability.ArkUI.ArkUI.Full
462
463**Parameters**
464
465| Name| Type                                                | Mandatory| Description                                                       |
466| ------ | ---------------------------------------------------- | ---- | ----------------------------------------------------------- |
467| value  | number \| [Resource](ts-types.md#resource) | Yes  | Friction coefficient.<br>Default value: **0.9** for wearable devices and **0.6** for non-wearable devices<br>Since API version 11, the default value for non-wearable devices is **0.7**.<br>Since API version 12, the default value for non-wearable devices is **0.75**.|
468
469### alignItems<sup>12+</sup>
470
471alignItems(alignment: Optional\<GridItemAlignment\>)
472
473Sets the alignment mode of grid items in the grid. For details about the usage, see [Example 9](#example-9-setting-grid-item-heights-based-on-the-tallest-item-in-the-current-row).
474
475**Atomic service API**: This API can be used in atomic services since API version 12.
476
477**System capability**: SystemCapability.ArkUI.ArkUI.Full
478
479**Parameters**
480
481| Name    | Type  | Mandatory| Description                           |
482| ---------- | ------ | ---- | ------------------------------- |
483| alignment | Optional\<[GridItemAlignment](#griditemalignment12)\> | Yes  | Alignment mode of grid items in the grid.<br>Default value: **GridItemAlignment.DEFAULT**|
484
485## GridItemAlignment<sup>12+</sup>
486
487Enumerates the alignment modes of grid items.
488
489**Atomic service API**: This API can be used in atomic services since API version 12.
490
491**System capability**: SystemCapability.ArkUI.ArkUI.Full
492
493| Name  | Value| Description                                |
494| ------ |------| -------------------------------------- |
495| DEFAULT  |  0  | Use the default alignment mode of the grid.|
496| STRETCH |  1  | Use the height of the tallest grid item in a row as the height for all other grid items in that row.|
497
498
499> **NOTE**
500>
501> 1. The **STRETCH** option only takes effect in scrollable grids.<br>
502> 2. The **STRETCH** option takes effect only if each grid item in a row is of a regular size (occupying only one row and one column). It is not effective in scenarios where there are grid items spanning across rows or columns.<br>
503> 3. When **STRETCH** is used, only grid items without a set height will adopt the height of the tallest grid item in the current row; the height of grid items with a set height will remain unchanged.<br>
504> 4. When **STRETCH** is used, the grid undergoes an additional layout process, which may incur additional performance overhead.
505
506## GridDirection<sup>8+</sup>
507
508Enumerates the main axis layout directions.
509
510**Atomic service API**: This API can be used in atomic services since API version 11.
511
512**System capability**: SystemCapability.ArkUI.ArkUI.Full
513
514| Name  |Value| Description                                |
515| ------ |------| -------------------------------------- |
516| Row  |  0  | Horizontal layout, where the child components are arranged from left to right as the main axis runs along the rows.|
517| Column |  1  | Vertical layout, where the child components are arranged from top to bottom as the main axis runs down the columns.|
518| RowReverse    |  2  | Reverse horizontal layout, where the child components are arranged from right to left as the main axis runs along the rows.|
519| ColumnReverse   |  3  | Reverse vertical layout, where the child components are arranged from bottom up as the main axis runs down the columns.|
520
521> **NOTE**
522>
523> The default value of the universal attribute [clip](ts-universal-attributes-sharp-clipping.md) is **true** for the **Grid** component.
524
525## Events
526
527In addition to [universal events](ts-component-general-events.md) and [scrollable component common events](ts-container-scrollable-common.md#events), the following events are also supported.
528
529### onScrollIndex
530
531onScrollIndex(event: (first: number, last: number) => void)
532
533Triggered when the first or last item displayed in the grid changes, that is, when the index of either the first or last item changes. It is triggered once when the grid is initialized.
534
535**Atomic service API**: This API can be used in atomic services since API version 11.
536
537**System capability**: SystemCapability.ArkUI.ArkUI.Full
538
539**Parameters**
540
541| Name            | Type  | Mandatory| Description                            |
542| ------------------ | ------ | ---- | -------------------------------- |
543| first              | number | Yes  | Index of the first item of the grid.|
544| last<sup>10+</sup> | number | Yes  | Index of the last item of the grid.|
545
546### onItemDragStart<sup>8+</sup>
547
548onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => (() => any) \| void)
549
550Triggered when a grid item starts to be dragged. If **void** is returned, the drag operation cannot be performed.
551
552This event is triggered when the user long presses a grid item.
553
554Drag gesture recognition is also initiated by a long press, and the event processing mechanism prioritizes child component events. Therefore, when the grid item is bound to the long press gesture, it cannot be dragged. In light of this, if both long press and drag operations are required on the grid item, you can use the universal drag event.
555
556**Atomic service API**: This API can be used in atomic services since API version 11.
557
558**System capability**: SystemCapability.ArkUI.ArkUI.Full
559
560**Parameters**
561
562| Name   | Type                                 | Mandatory| Description                  |
563| --------- | ------------------------------------- | ---- | ---------------------- |
564| event     | [ItemDragInfo](ts-container-scrollable-common.md#itemdraginfo) | Yes  | Information about the drag point.        |
565| itemIndex | number                                | Yes  | Index of the dragged item.|
566
567### onItemDragEnter<sup>8+</sup>
568
569onItemDragEnter(event: (event: ItemDragInfo) => void)
570
571Triggered when the dragged item enters the drop target of the grid.
572
573**Atomic service API**: This API can be used in atomic services since API version 11.
574
575**System capability**: SystemCapability.ArkUI.ArkUI.Full
576
577**Parameters**
578
579| Name| Type                                 | Mandatory| Description          |
580| ------ | ------------------------------------- | ---- | -------------- |
581| event  | [ItemDragInfo](ts-container-scrollable-common.md#itemdraginfo) | Yes  | Information about the drag point.|
582
583### onItemDragMove<sup>8+</sup>
584
585onItemDragMove(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number) => void)
586
587Triggered when the dragged item moves over the drop target of the grid.
588
589**Atomic service API**: This API can be used in atomic services since API version 11.
590
591**System capability**: SystemCapability.ArkUI.ArkUI.Full
592
593**Parameters**
594
595| Name     | Type                                 | Mandatory| Description          |
596| ----------- | ------------------------------------- | ---- | -------------- |
597| event       | [ItemDragInfo](ts-container-scrollable-common.md#itemdraginfo) | Yes  | Information about the drag point.|
598| itemIndex   | number                                | Yes  | Initial position of the dragged item.|
599| insertIndex | number                                | Yes  | Index of the position to which the dragged item is dropped.|
600
601### onItemDragLeave<sup>8+</sup>
602
603onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void)
604
605Triggered when the dragged item leaves the drop target of the grid.
606
607**Atomic service API**: This API can be used in atomic services since API version 11.
608
609**System capability**: SystemCapability.ArkUI.ArkUI.Full
610
611**Parameters**
612
613| Name   | Type                                 | Mandatory| Description                      |
614| --------- | ------------------------------------- | ---- | -------------------------- |
615| event     | [ItemDragInfo](ts-container-scrollable-common.md#itemdraginfo) | Yes  | Information about the drag point.            |
616| itemIndex | number                                | Yes  | Index of the dragged item.|
617
618### onItemDrop<sup>8+</sup>
619
620onItemDrop(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => void)
621
622Triggered when the dragged grid item is dropped on the drop target of the grid.
623
624**isSuccess** returns **true** if the grid item is dropped within the grid, and returns **false** otherwise.
625
626**Atomic service API**: This API can be used in atomic services since API version 11.
627
628**System capability**: SystemCapability.ArkUI.ArkUI.Full
629
630**Parameters**
631
632| Name     | Type                                 | Mandatory| Description          |
633| ----------- | ------------------------------------- | ---- | -------------- |
634| event       | [ItemDragInfo](ts-container-scrollable-common.md#itemdraginfo) | Yes  | Information about the drag point.|
635| itemIndex   | number                                | Yes  | Initial position of the dragged item.|
636| insertIndex | number                                | Yes  | Index of the position to which the dragged item is dropped.|
637| isSuccess   | boolean                               | Yes  | Whether the dragged item is successfully dropped.  |
638
639### onScrollBarUpdate<sup>10+</sup>
640
641onScrollBarUpdate(event: (index: number, offset: number) => ComputedBarAttribute)
642
643Triggered when the first item displayed in the grid changes. You can use the callback to set the position and length of the scrollbar.
644
645This API is intended solely for setting the scroll position of the grid. Avoid implementing service logic within this API.
646
647**Atomic service API**: This API can be used in atomic services since API version 11.
648
649**System capability**: SystemCapability.ArkUI.ArkUI.Full
650
651**Parameters**
652
653| Name| Type  | Mandatory| Description                                                        |
654| ------ | ------ | ---- | ------------------------------------------------------------ |
655| index  | number | Yes  | Index of the first item of the grid.                            |
656| offset | number | Yes  | Offset of the displayed first item relative to the start position of the grid, in vp.|
657
658**Return value**
659
660| Type                                                 | Description                |
661| ----------------------------------------------------- | -------------------- |
662| [ComputedBarAttribute](#computedbarattribute10) | Position and length of the scrollbar.|
663
664### onReachStart<sup>10+</sup>
665
666onReachStart(event: () => void)
667
668Triggered when the grid reaches the start position.
669
670This event is triggered once when the grid is initialized and once when the grid scrolls to the start position. If the edge effect is set to a spring effect, this event is triggered once when the swipe passes the initial position, and triggered again when the swipe rebounds back to the initial position.
671
672**Atomic service API**: This API can be used in atomic services since API version 11.
673
674**System capability**: SystemCapability.ArkUI.ArkUI.Full
675
676### onReachEnd<sup>10+</sup>
677
678onReachEnd(event: () => void)
679
680Triggered when the grid reaches the end position.
681
682If the edge effect is set to a spring effect, this event is triggered once when the swipe passes the end position, and triggered again when the swipe rebounds back to the end position.
683
684**Atomic service API**: This API can be used in atomic services since API version 11.
685
686**System capability**: SystemCapability.ArkUI.ArkUI.Full
687
688### onScrollFrameBegin<sup>10+</sup>
689
690onScrollFrameBegin(event: (offset: number, state:  ScrollState) => { offsetRemain: number })
691
692Triggered when the grid starts to scroll. After the amount by which the grid will scroll is passed in, the event handler works out the amount by which the grid needs to scroll based on the real-world situation and returns the result.
693
694**Atomic service API**: This API can be used in atomic services since API version 11.
695
696**System capability**: SystemCapability.ArkUI.ArkUI.Full
697
698**Parameters**
699
700| Name| Type                                                   | Mandatory| Description                      |
701| ------ | ------------------------------------------------------- | ---- | -------------------------- |
702| offset | number                                                  | Yes  | Amount to scroll by, in vp.|
703| state  | [ScrollState](ts-container-list.md#scrollstate) | Yes  | Current scroll state.            |
704
705**Return value**
706
707| Type                    | Description                |
708| ------------------------ | -------------------- |
709| { offsetRemain: number } | Actual amount by which the grid scrolls, in vp.|
710
711### onScrollStart<sup>10+</sup>
712
713onScrollStart(event: () => void)
714
715Triggered when the grid starts scrolling initiated by the user's finger dragging the grid or its scrollbar. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) starts.
716
717**Atomic service API**: This API can be used in atomic services since API version 11.
718
719**System capability**: SystemCapability.ArkUI.ArkUI.Full
720
721### onScrollStop<sup>10+</sup>
722
723onScrollStop(event: () => void)
724
725Triggered when the grid stops scrolling after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) stops.
726
727**Atomic service API**: This API can be used in atomic services since API version 11.
728
729**System capability**: SystemCapability.ArkUI.ArkUI.Full
730
731### onScroll<sup>(deprecated)</sup>
732onScroll(event: (scrollOffset: number, scrollState: [ScrollState](ts-container-list.md#scrollstate)) => void)
733
734Triggered when the grid scrolls.
735
736This API is available since API version 10.
737
738This API is deprecated since API version 12. You are advised to use [onDidScroll](ts-container-scrollable-common.md#ondidscroll12) instead.
739
740**Atomic service API**: This API can be used in atomic services since API version 11.
741
742**System capability**: SystemCapability.ArkUI.ArkUI.Full
743
744**Parameters**
745
746| Name| Type| Mandatory| Description|
747| ------ | ------ | ------ | ------|
748| scrollOffset | number | Yes| Scroll offset of each frame. The offset is positive when the grid is scrolled up and negative when the grid is scrolled down.<br>Unit: vp|
749| scrollState | [ScrollState](ts-container-list.md#scrollstate) | Yes| Current scroll state.|
750
751## ComputedBarAttribute<sup>10+</sup>
752
753Provides information about the position and length of the scrollbar.
754
755**Atomic service API**: This API can be used in atomic services since API version 11.
756
757**System capability**: SystemCapability.ArkUI.ArkUI.Full
758
759| Name        | Type        | Read Only| Optional|   Description        |
760| ----------- | ------------ | ---- | ---- | ---------- |
761| totalOffset | number | No| No|  Total offset of the grid content relative to the display area, in px.   |
762| totalLength   | number | No| No|  Total length of the grid content, in px.   |
763
764## Example
765
766### Example 1: Creating a Fixed Row and Column Grid Layout
767
768This example demonstrates how to use **onGetRectByIndex** in **GridLayoutOptions** to define the position and size of each grid item.
769
770```ts
771// xxx.ets
772@Entry
773@Component
774struct GridExample {
775  @State numbers1: String[] = ['0', '1', '2', '3', '4']
776  @State numbers2: String[] = ['0', '1','2','3','4','5']
777
778  layoutOptions3: GridLayoutOptions = {
779    regularSize: [1, 1],
780    onGetRectByIndex: (index: number) => {
781      if (index == 0)
782        return [0, 0, 1, 1]
783      else if(index==1)
784        return [0, 1, 2, 2]
785      else if(index==2)
786        return [0 ,3 ,3 ,3]
787      else if(index==3)
788        return [3, 0, 3, 3]
789      else if(index==4)
790        return [4, 3, 2, 2]
791      else
792        return [5, 5, 1, 1]
793    }
794  }
795
796  build() {
797    Column({ space: 5 }) {
798      Grid() {
799        ForEach(this.numbers1, (day: string) => {
800          ForEach(this.numbers1, (day: string) => {
801            GridItem() {
802              Text(day)
803                .fontSize(16)
804                .backgroundColor(0xF9CF93)
805                .width('100%')
806                .height('100%')
807                .textAlign(TextAlign.Center)
808            }
809          }, (day: string) => day)
810        }, (day: string) => day)
811      }
812      .columnsTemplate('1fr 1fr 1fr 1fr 1fr')
813      .rowsTemplate('1fr 1fr 1fr 1fr 1fr')
814      .columnsGap(10)
815      .rowsGap(10)
816      .width('90%')
817      .backgroundColor(0xFAEEE0)
818      .height(300)
819
820      Text('Use of GridLayoutOptions: onGetRectByIndex').fontColor(0xCCCCCC).fontSize(9).width('90%')
821
822      Grid(undefined, this.layoutOptions3) {
823        ForEach(this.numbers2, (day: string) => {
824          GridItem() {
825            Text(day)
826              .fontSize(16)
827              .backgroundColor(0xF9CF93)
828              .width('100%')
829              .height("100%")
830              .textAlign(TextAlign.Center)
831          }
832          .height("100%")
833          .width('100%')
834        }, (day: string) => day)
835      }
836      .columnsTemplate('1fr 1fr 1fr 1fr 1fr 1fr')
837      .rowsTemplate('1fr 1fr 1fr 1fr 1fr 1fr')
838      .columnsGap(10)
839      .rowsGap(10)
840      .width('90%')
841      .backgroundColor(0xFAEEE0)
842      .height(300)
843    }.width('100%').margin({ top: 5 })
844  }
845}
846```
847
848![en-us_image_0000001219744183](figures/en-us_image_0000001219744183.gif)
849
850### Example 2: Implementing a Scrollable Grid with Scroll Events
851
852This example shows a scrollable grid with all its scrolling attributes and events specified.
853
854```ts
855// xxx.ets
856@Entry
857@Component
858struct GridExample {
859  @State numbers: String[] = ['0', '1', '2', '3', '4']
860  scroller: Scroller = new Scroller()
861  @State gridPosition: number = 0 // 0 indicates scrolling to the top of the grid, 1 indicates scrolling to the center, and 2 indicates scrolling to the bottom.
862
863  build() {
864    Column({ space: 5 }) {
865      Text('scroll').fontColor(0xCCCCCC).fontSize(9).width('90%')
866      Grid(this.scroller) {
867        ForEach(this.numbers, (day: string) => {
868          ForEach(this.numbers, (day: string) => {
869            GridItem() {
870              Text(day)
871                .fontSize(16)
872                .backgroundColor(0xF9CF93)
873                .width('100%')
874                .height(80)
875                .textAlign(TextAlign.Center)
876            }
877          }, (day: string) => day)
878        }, (day: string) => day)
879      }
880      .columnsTemplate('1fr 1fr 1fr 1fr 1fr')
881      .columnsGap(10)
882      .rowsGap(10)
883      .friction(0.6)
884      .enableScrollInteraction(true)
885      .supportAnimation(false)
886      .multiSelectable(false)
887      .edgeEffect(EdgeEffect.Spring)
888      .scrollBar(BarState.On)
889      .scrollBarColor(Color.Grey)
890      .scrollBarWidth(4)
891      .width('90%')
892      .backgroundColor(0xFAEEE0)
893      .height(300)
894      .onScrollIndex((first: number, last: number) => {
895        console.info(first.toString())
896        console.info(last.toString())
897      })
898      .onScrollBarUpdate((index: number, offset: number) => {
899        console.info("XXX" + 'Grid onScrollBarUpdate,index : ' + index.toString() + ",offset" + offset.toString())
900        return { totalOffset: (index / 5) * (80 + 10) - offset, totalLength: 80 * 5 + 10 * 4 }
901      }) // The sample code applies only to the current data source. If the data source changes, modify the code or delete this attribute.
902      .onDidScroll((scrollOffset: number, scrollState: ScrollState) => {
903        console.info(scrollOffset.toString())
904        console.info(scrollState.toString())
905      })
906      .onScrollStart(() => {
907        console.info("XXX" + "Grid onScrollStart")
908      })
909      .onScrollStop(() => {
910        console.info("XXX" + "Grid onScrollStop")
911      })
912      .onReachStart(() => {
913        this.gridPosition = 0
914        console.info("XXX" + "Grid onReachStart")
915      })
916      .onReachEnd(() => {
917        this.gridPosition = 2
918        console.info("XXX" + "Grid onReachEnd")
919      })
920
921      Button('next page')
922        .onClick(() => {// Click to go to the next page.
923          this.scroller.scrollPage({ next: true })
924        })
925    }.width('100%').margin({ top: 5 })
926  }
927}
928```
929
930![scrollerExample2](figures/scrollerExample2.gif)
931
932### Example 3: Implementing a Scrollable Grid with Grid Items Spanning Rows and Columns
933
934This example shows how to use **irregularIndexes** and **onGetIrregularSizeByIndex** in **GridLayoutOptions** to define custom sizes and spans for grid items.
935
936```ts
937// xxx.ets
938@Entry
939@Component
940struct GridExample {
941  @State numbers: String[] = ['0', '1', '2', '3', '4']
942  scroller: Scroller = new Scroller()
943  layoutOptions1: GridLayoutOptions = {
944    regularSize: [1, 1],        // Only [1, 1] is supported.
945    irregularIndexes: [0, 6],   // The grid item whose indexes are 0 and 6 occupies one row.
946  }
947
948  layoutOptions2: GridLayoutOptions = {
949    regularSize: [1, 1],
950    irregularIndexes: [0, 7],   // The number of columns occupied by the grid item whose indexes are 0 and 7 is specified by onGetIrregularSizeByIndex.
951    onGetIrregularSizeByIndex: (index: number) => {
952      if (index === 0) {
953        return [1, 5]
954      }
955      return [1, index % 6 + 1]
956    }
957  }
958
959  build() {
960    Column({ space: 5 }) {
961      Grid(this.scroller, this.layoutOptions1) {
962        ForEach(this.numbers, (day: string) => {
963          ForEach(this.numbers, (day: string) => {
964            GridItem() {
965              Text(day)
966                .fontSize(16)
967                .backgroundColor(0xF9CF93)
968                .width('100%')
969                .height(80)
970                .textAlign(TextAlign.Center)
971            }.selectable(false)
972          }, (day: string) => day)
973        }, (day: string) => day)
974      }
975      .columnsTemplate('1fr 1fr 1fr 1fr 1fr')
976      .columnsGap(10)
977      .rowsGap(10)
978      .multiSelectable(true)
979      .scrollBar(BarState.Off)
980      .width('90%')
981      .backgroundColor(0xFAEEE0)
982      .height(300)
983
984      Text('scroll').fontColor(0xCCCCCC).fontSize(9).width('90%')
985      // The grid does not scroll, and undefined is used to reserve space.
986      Grid(undefined, this.layoutOptions2) {
987        ForEach(this.numbers, (day: string) => {
988          ForEach(this.numbers, (day: string) => {
989            GridItem() {
990              Text(day)
991                .fontSize(16)
992                .backgroundColor(0xF9CF93)
993                .width('100%')
994                .height(80)
995                .textAlign(TextAlign.Center)
996            }
997          }, (day: string) => day)
998        }, (day: string) => day)
999      }
1000      .columnsTemplate('1fr 1fr 1fr 1fr 1fr')
1001      .columnsGap(10)
1002      .rowsGap(10)
1003      .scrollBar(BarState.Off)
1004      .width('90%')
1005      .backgroundColor(0xFAEEE0)
1006      .height(300)
1007    }.width('100%').margin({ top: 5 })
1008  }
1009}
1010```
1011
1012![gridLayoutOptions](figures/gridLayoutOptions.gif)
1013
1014### Example 4: Implementing Nested Scrolling in a Grid
1015
1016This example illustrates how to implement nested scrolling in a grid, using **nestedScroll** and **onScrollFrameBegin**:
1017
1018```ts
1019@Entry
1020@Component
1021struct GridExample {
1022  @State colors: number[] = [0xFFC0CB, 0xDA70D6, 0x6B8E23, 0x6A5ACD, 0x00FFFF, 0x00FF7F]
1023  @State numbers: number[] = []
1024  @State translateY: number = 0
1025  private scroller: Scroller = new Scroller()
1026  private gridScroller: Scroller = new Scroller()
1027  private touchDown: boolean = false
1028  private listTouchDown: boolean = false
1029  private scrolling: boolean = false
1030
1031  aboutToAppear() {
1032    for (let i = 0; i < 100; i++) {
1033      this.numbers.push(i)
1034    }
1035  }
1036
1037  build() {
1038    Stack() {
1039      Column() {
1040        Row() {
1041          Text('Head')
1042        }
1043
1044        Column() {
1045          List({ scroller: this.scroller }) {
1046            ListItem() {
1047              Grid() {
1048                GridItem() {
1049                  Text('GoodsTypeList1')
1050                }
1051                .backgroundColor(this.colors[0])
1052                .columnStart(0)
1053                .columnEnd(1)
1054
1055                GridItem() {
1056                  Text('GoodsTypeList2')
1057                }
1058                .backgroundColor(this.colors[1])
1059                .columnStart(0)
1060                .columnEnd(1)
1061
1062                GridItem() {
1063                  Text('GoodsTypeList3')
1064                }
1065                .backgroundColor(this.colors[2])
1066                .columnStart(0)
1067                .columnEnd(1)
1068
1069                GridItem() {
1070                  Text('GoodsTypeList4')
1071                }
1072                .backgroundColor(this.colors[3])
1073                .columnStart(0)
1074                .columnEnd(1)
1075
1076                GridItem() {
1077                  Text('GoodsTypeList5')
1078                }
1079                .backgroundColor(this.colors[4])
1080                .columnStart(0)
1081                .columnEnd(1)
1082              }
1083              .scrollBar(BarState.Off)
1084              .columnsGap(15)
1085              .rowsGap(10)
1086              .rowsTemplate('1fr 1fr 1fr 1fr 1fr')
1087              .columnsTemplate('1fr')
1088              .width('100%')
1089              .height(200)
1090            }
1091
1092            ListItem() {
1093              Grid(this.gridScroller) {
1094                ForEach(this.numbers, (item: number) => {
1095                  GridItem() {
1096                    Text(item + '')
1097                      .fontSize(16)
1098                      .backgroundColor(0xF9CF93)
1099                      .width('100%')
1100                      .height('100%')
1101                      .textAlign(TextAlign.Center)
1102                  }
1103                  .width('100%')
1104                  .height(40)
1105                  .shadow({ radius: 10, color: '#909399', offsetX: 1, offsetY: 1 })
1106                  .borderRadius(10)
1107                  .translate({ x: 0, y: this.translateY })
1108                }, (item: string) => item)
1109              }
1110              .columnsTemplate('1fr 1fr')
1111              .friction(0.3)
1112              .columnsGap(15)
1113              .rowsGap(10)
1114              .scrollBar(BarState.Off)
1115              .width('100%')
1116              .height('100%')
1117              .layoutDirection(GridDirection.Column)
1118              .nestedScroll({
1119                scrollForward: NestedScrollMode.PARENT_FIRST,
1120                scrollBackward: NestedScrollMode.SELF_FIRST
1121              })
1122              .onTouch((event: TouchEvent) => {
1123                if (event.type == TouchType.Down) {
1124                  this.listTouchDown = true
1125                } else if (event.type == TouchType.Up) {
1126                  this.listTouchDown = false
1127                }
1128              })
1129            }
1130          }
1131          .scrollBar(BarState.Off)
1132          .edgeEffect(EdgeEffect.None)
1133          .onTouch((event: TouchEvent) => {
1134            if (event.type == TouchType.Down) {
1135              this.touchDown = true
1136            } else if (event.type == TouchType.Up) {
1137              this.touchDown = false
1138            }
1139          })
1140          .onScrollFrameBegin((offset: number, state: ScrollState) => {
1141            if (this.scrolling && offset > 0) {
1142              let newOffset = this.scroller.currentOffset().yOffset
1143              if (newOffset >= 590) {
1144                this.gridScroller.scrollBy(0, offset)
1145                return { offsetRemain: 0 }
1146              } else if (newOffset + offset > 590) {
1147                this.gridScroller.scrollBy(0, newOffset + offset - 590)
1148                return { offsetRemain: 590 - newOffset }
1149              }
1150            }
1151            return { offsetRemain: offset }
1152          })
1153          .onScrollStart(() => {
1154            if (this.touchDown && !this.listTouchDown) {
1155              this.scrolling = true
1156            }
1157          })
1158          .onScrollStop(() => {
1159            this.scrolling = false
1160          })
1161        }
1162        .width('100%')
1163        .height('100%')
1164        .padding({ left: 10, right: 10 })
1165      }
1166
1167      Row() {
1168        Text('Top')
1169          .width(30)
1170          .height(30)
1171          .borderRadius(50)
1172      }
1173      .padding(5)
1174      .borderRadius(50)
1175      .backgroundColor('#ffffff')
1176      .shadow({ radius: 10, color: '#909399', offsetX: 1, offsetY: 1 })
1177      .margin({ right: 22, bottom: 15 })
1178      .onClick(() => {
1179        this.scroller.scrollTo({ xOffset: 0, yOffset: 0 })
1180        this.gridScroller.scrollTo({ xOffset: 0, yOffset: 0 })
1181      })
1182    }
1183    .align(Alignment.BottomEnd)
1184  }
1185}
1186```
1187
1188![nestedScrollExample4](figures/nestedScrollExample4.gif)
1189
1190### Example 5: Implementing Dragging in a Grid
1191
11921.  Set **editMode\(true\)** to enable edit mode, where the user can drag the grid items.
11932.  In the [onItemDragStart](#onitemdragstart8) callback, set the image to be displayed during dragging.
11943.  Through [onItemDrop](#onitemdrop8), obtain the initial position of the dragged item and the position to which the dragged item will be dropped. Through [onItemDrop](#onitemdrop8), complete the array position exchange logic.
1195
1196> **NOTE**
1197>
1198> The drag and drop action is not displayed in the preview.
1199
1200```ts
1201@Entry
1202@Component
1203struct GridExample {
1204  @State numbers: string[] = []
1205  scroller: Scroller = new Scroller()
1206  @State text: string = 'drag'
1207
1208  @Builder pixelMapBuilder () { // Style for the drag event.
1209    Column() {
1210      Text(this.text)
1211        .fontSize(16)
1212        .backgroundColor(0xF9CF93)
1213        .width(80)
1214        .height(80)
1215        .textAlign(TextAlign.Center)
1216    }
1217  }
1218
1219  aboutToAppear() {
1220    for (let i = 1;i <= 15; i++) {
1221      this.numbers.push(i + '')
1222    }
1223  }
1224
1225  changeIndex(index1: number, index2: number) { // Exchange the array position.
1226    let temp: string;
1227    temp = this.numbers[index1];
1228    this.numbers[index1] = this.numbers[index2];
1229    this.numbers[index2] = temp;
1230  }
1231
1232  build() {
1233    Column({ space: 5 }) {
1234      Grid(this.scroller) {
1235        ForEach(this.numbers, (day: string) => {
1236          GridItem() {
1237            Text(day)
1238              .fontSize(16)
1239              .backgroundColor(0xF9CF93)
1240              .width(80)
1241              .height(80)
1242              .textAlign(TextAlign.Center)
1243          }
1244        })
1245      }
1246      .columnsTemplate('1fr 1fr 1fr')
1247      .columnsGap(10)
1248      .rowsGap(10)
1249      .width('90%')
1250      .backgroundColor(0xFAEEE0)
1251      .height(300)
1252      .editMode(true) // Enable edit mode, where the user can drag the grid items.
1253      .onItemDragStart((event: ItemDragInfo, itemIndex: number) => { // Triggered when a grid item starts to be dragged.
1254        this.text = this.numbers[itemIndex]
1255        return this.pixelMapBuilder() // Set the image to be displayed during dragging.
1256      })
1257      .onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => { // Triggered when the dragged item is dropped on the drop target of the grid.
1258        // If isSuccess is set to false, the item is dropped outside of the grid. If the value of insertIndex is greater than that of length, an item adding event occurs.
1259        if (!isSuccess || insertIndex >= this.numbers.length) {
1260          return
1261        }
1262        console.info('beixiang' + itemIndex + '', insertIndex + '') // itemIndex indicates the initial position of the dragged item. insertIndex indicates the position to which the dragged item will be dropped.
1263        this.changeIndex(itemIndex, insertIndex)
1264      })
1265    }.width('100%').margin({ top: 5 })
1266  }
1267}
1268```
1269
1270Below are some examples.
1271
1272Below shows how the grid looks when dragging of grid items starts.
1273
1274![gridDrag](figures/gridDrag.png)
1275
1276Below shows how the grid looks when dragging of grid items is in progress.
1277
1278![gridDrag](figures/gridDrag1.png)
1279
1280Below shows how the grid looks after grid item 1 and grid item 6 swap their positions.
1281
1282![gridDrag](figures/gridDrag2.png)
1283
1284### Example 6: Implementing Adaptive Grid Layout
1285
1286This example demonstrates the use of **layoutDirection**, **maxcount**, **minCount**, and **cellLength**:
1287
1288```ts
1289@Entry
1290@Component
1291struct GridExample {
1292  @State numbers: string[] = []
1293
1294  aboutToAppear() {
1295    for (let i = 1; i <= 30; i++) {
1296      this.numbers.push(i + '')
1297    }
1298  }
1299
1300  build() {
1301    Scroll() {
1302      Column({ space: 5 }) {
1303        Blank()
1304        Text('The layoutDirection, maxcount, minCount, and cellLength parameters take effect only when neither rowsTemplate nor columnsTemplate is set.')
1305          .fontSize(15).fontColor(0xCCCCCC).width('90%')
1306        Grid() {
1307          ForEach(this.numbers, (day: string) => {
1308            GridItem() {
1309              Text(day).fontSize(16).backgroundColor(0xF9CF93)
1310            }.width(40).height(80).borderWidth(2).borderColor(Color.Red)
1311          }, (day: string) => day)
1312        }
1313        .height(300)
1314        .columnsGap(10)
1315        .rowsGap(10)
1316        .backgroundColor(0xFAEEE0)
1317        .maxCount(6)
1318        .minCount(2)
1319        .cellLength(0)
1320        .layoutDirection(GridDirection.Row)
1321      }
1322      .width('90%').margin({ top: 5, left: 5, right: 5 })
1323      .align(Alignment.Center)
1324    }
1325  }
1326}
1327```
1328
1329![cellLength](figures/cellLength.gif)
1330
1331### Example 7: Dynamically Adjusting the Number of Grid Columns with a Pinch Gesture
1332
1333This example demonstrates how to adjust the number of columns in the grid with a pinch gesture using two fingers.
1334
1335```ts
1336// xxx.ets
1337@Entry
1338@Component
1339struct GridExample {
1340  @State numbers: String[] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19']
1341  @State columns: number = 2
1342
1343  aboutToAppear() {
1344    let lastCount = AppStorage.get<number>('columnsCount')
1345    if (typeof lastCount != 'undefined') {
1346      this.columns = lastCount
1347    }
1348  }
1349
1350  build() {
1351    Column({ space: 5 }) {
1352      Row() {
1353        Text('Pinch to change the number of columns')
1354          .height('5%')
1355          .margin({ top: 10, left: 20 })
1356      }
1357
1358      Grid() {
1359        ForEach(this.numbers, (day: string) => {
1360          ForEach(this.numbers, (day: string) => {
1361            GridItem() {
1362              Text(day)
1363                .fontSize(16)
1364                .backgroundColor(0xF9CF93)
1365                .width('100%')
1366                .height(80)
1367                .textAlign(TextAlign.Center)
1368            }
1369          }, (day: string) => day)
1370        }, (day: string) => day)
1371      }
1372      .columnsTemplate('1fr '.repeat(this.columns))
1373      .columnsGap(10)
1374      .rowsGap(10)
1375      .width('90%')
1376      .scrollBar(BarState.Off)
1377      .backgroundColor(0xFAEEE0)
1378      .height('100%')
1379      .cachedCount(3)
1380      // Switching the number of columns triggers a reordering animation for the item positions.
1381      .animation({
1382        duration: 300,
1383        curve: Curve.Smooth
1384      })
1385      .priorityGesture(
1386        PinchGesture()
1387          .onActionEnd((event: GestureEvent) => {
1388            console.info('end scale:' + event.scale)
1389            // When a user performs a pinch-to-zoom gesture by moving their fingers apart, and the number of columns decreases to a certain threshold (in this case, 2), it will cause the items to enlarge.
1390            if (event.scale > 2) {
1391              this.columns--
1392            } else if (event.scale < 0.6) {
1393              this.columns++
1394            }
1395            // You can set the maximum and minimum number of columns based on the device screen width. Here, the minimum number of columns is 1, and the maximum number of columns is 4.
1396            this.columns = Math.min(4, Math.max(1, this.columns));
1397            AppStorage.setOrCreate<number>('columnsCount', this.columns)
1398          })
1399      )
1400    }.width('100%').margin({ top: 5 })
1401  }
1402}
1403```
1404
1405![pinch](figures/grid-pinch.gif)
1406
1407### Example 8: Using Adaptive Column Count Settings
1408This example shows the usage of **auto-fill**, **auto-fit**, and **auto-stretch** in [columnsTemplate](#columnstemplate).
1409
1410```ts
1411@Entry
1412@Component
1413struct GridColumnsTemplate {
1414  data: number[] = [0, 1, 2, 3, 4, 5]
1415  data1: number[] = [0, 1, 2, 3, 4, 5]
1416  data2: number[] = [0, 1, 2, 3, 4, 5]
1417
1418  build() {
1419    Column({ space: 10 }) {
1420      Text('auto-fill auto-calculates the number of columns based on the set column width').width('90%')
1421      Grid() {
1422        ForEach(this.data, (item: number) => {
1423          GridItem() {
1424            Text('N' + item).height(80)
1425          }
1426          .backgroundColor(Color.Orange)
1427        })
1428      }
1429      .width('90%')
1430      .border({ width: 1, color: Color.Black })
1431      .columnsTemplate('repeat(auto-fill, 70)')
1432      .columnsGap(10)
1433      .rowsGap(10)
1434      .height(150)
1435
1436      Text('auto-fit calculates the number of columns based on the specified column width, and then any remaining space is evenly distributed across all columns').width('90%')
1437      Grid() {
1438        ForEach(this.data1, (item: number) => {
1439          GridItem() {
1440            Text('N' + item).height(80)
1441          }
1442          .backgroundColor(Color.Orange)
1443        })
1444      }
1445      .width('90%')
1446      .border({ width: 1, color: Color.Black })
1447      .columnsTemplate('repeat(auto-fit, 70)')
1448      .columnsGap(10)
1449      .rowsGap(10)
1450      .height(150)
1451
1452      Text('auto-stretch calculates the number of columns based on the specified column width, and then any remaining space is evenly distributed into the gaps between columns').width('90%')
1453      Grid() {
1454        ForEach(this.data2, (item: number) => {
1455          GridItem() {
1456            Text('N' + item).height(80)
1457          }
1458          .backgroundColor(Color.Orange)
1459        })
1460      }
1461      .width('90%')
1462      .border({ width: 1, color: Color.Black })
1463      .columnsTemplate('repeat(auto-stretch, 70)')
1464      .columnsGap(10)
1465      .rowsGap(10)
1466      .height(150)
1467    }
1468    .width('100%')
1469    .height('100%')
1470  }
1471}
1472```
1473
1474![gridColumnsTemplate](figures/gridColumnsTemplate.png)
1475
1476### Example 9: Setting Grid Item Heights Based on the Tallest Item in the Current Row
1477This example implements a grid that contains two columns. The grid item in each column consists of two **Column** components with determined heights and one **Text** component with an undetermined height.
1478
1479By default, the heights of the left and right grid items may differ; however, after the grid's **alignItems** attribute is set to **GridItemAlignment.STRETCH**, the grid item with a shorter height in a row will adopt the height of the taller grid item, aligning their heights within the same row.
1480
1481```ts
1482@Entry
1483@Component
1484struct Index {
1485  @State data: number[] = [];
1486  @State items: number[] = [];
1487
1488  aboutToAppear(): void {
1489    for (let i = 0; i < 100; i++) {
1490      this.data.push(i)
1491      this.items.push(this.getSize())
1492    }
1493  }
1494
1495  getSize() {
1496    let ret = Math.floor(Math.random() * 5)
1497    return Math.max(1, ret)
1498  }
1499
1500  build() {
1501    Column({ space: 10 }) {
1502      Text('Grid alignItems sample code')
1503
1504      Grid() {
1505        ForEach(this.data, (item: number) => {
1506          // GridItem and Column components, when left without explicitly set heights, will by default adapt to the size of their child components. With alignItems set to STRETCH, they will instead take on the height of the tallest component in the current row.
1507          // If the height is explicitly set, the component maintains the defined height and will not follow the height of the tallest component in the current row.
1508          GridItem() {
1509            Column() {
1510              Column().height(100).backgroundColor('#D5D5D5').width('100%')
1511              // The Text component in the center is set with flexGrow(1) to automatically fill the available space within the parent component.
1512              Text('This is a piece of text.'.repeat(this.items[item]))
1513                .flexGrow(1).width('100%').align(Alignment.TopStart)
1514                .backgroundColor('#F7F7F7')
1515              Column().height(50).backgroundColor('#707070').width('100%')
1516            }
1517          }
1518          .border({ color: Color.Black, width: 1 })
1519        })
1520      }
1521      .columnsGap(10)
1522      .rowsGap(5)
1523      .columnsTemplate('1fr 1fr')
1524      .width('80%')
1525      .height('100%')
1526      // When the grid has its alignItems attribute set to STRETCH, it adjusts the height of all grid items in a row to match the height of the tallest grid item in that row.
1527      .alignItems(GridItemAlignment.STRETCH)
1528      .scrollBar(BarState.Off)
1529    }
1530    .height('100%')
1531    .width('100%')
1532  }
1533}
1534
1535```
1536![gridAlignItems](figures/gridAlignItems.png)
1537
1538### Example 10: Setting Edge Fading
1539This example demonstrates how to enable the edge fading effect using [fadingEdge](ts-container-scrollable-common.md#fadingedge14).
1540
1541```ts
1542// xxx.ets
1543// This example demonstrates how to implement a Grid component with an edge fading effect and set the length of the fading edge.
1544import { LengthMetrics } from '@kit.ArkUI'
1545@Entry
1546@Component
1547struct GridExample {
1548  @State numbers: String[] = ['0', '1', '2', '3', '4']
1549  @State rowNumbers: String[] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
1550  scroller: Scroller = new Scroller()
1551
1552  build() {
1553    Column({ space: 5 }) {
1554      Text('scroll').fontColor(0xCCCCCC).fontSize(9).width('90%')
1555      Grid(this.scroller) {
1556        ForEach(this.rowNumbers, (day: string) => {
1557          ForEach(this.numbers, (day: string) => {
1558            GridItem() {
1559              Text(day)
1560                .fontSize(16)
1561                .backgroundColor(0xF9CF93)
1562                .width('100%')
1563                .height(80)
1564                .textAlign(TextAlign.Center)
1565            }
1566          }, (day: string) => day)
1567        }, (day: string) => day)
1568      }
1569      .columnsTemplate('1fr 1fr 1fr 1fr 1fr')
1570      .columnsGap(10)
1571      .rowsGap(20)
1572      .height('90%')
1573      .fadingEdge(true,{fadingEdgeLength:LengthMetrics.vp(80)})
1574
1575    }.width('100%').margin({ top: 5 })
1576  }
1577}
1578```
1579
1580![fadingEdge_grid](figures/fadingEdge_grid.gif)