• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Creating a List
2
3
4## Overview
5
6A list is a container that displays a collection of items. If the list items go beyond the screen, the list can scroll to reveal the content off the screen. A list is applicable for presenting similar data types or data type sets, such as images and text. For example, it can be used to present a collection of contacts, songs, and items to shop.
7
8Use lists to easily and efficiently display structured, scrollable information. You can provide a single view of rows or columns by arranging the [\<ListItemGroup>](../reference/arkui-ts/ts-container-listitemgroup.md) or [\<ListItem>](../reference/arkui-ts/ts-container-listitem.md) child components linearly in a vertical or horizontal direction in the [\<List>](../reference/arkui-ts/ts-container-list.md) component, or use [ForEach](../quick-start/arkts-rendering-control-foreach.md) to iterate over a group of rows or columns, or mix any number of single views and **ForEach** structures to build a list. The **\<List>** component supports the generation of child components in various [rendering](../quick-start/arkts-rendering-control-overview.md) modes, including conditional rendering, rendering of repeated content, and lazy data loading.
9
10
11## Layout and Constraints
12
13A list automatically arranges child components in the direction it scrolls. Adding or removing child components from the list will trigger re-arrangement of the child components.
14
15As shown in the following figure, in a vertical list, **\<ListItemGroup>** or **\<ListItem>** components are automatically arranged vertically.
16
17**\<ListItemGroup>** is used to display list data by group. Its child component is also **\<ListItem>**. **\<ListItem>** represents a list item, which can contain a single child component.
18
19  **Figure 1** Relationships between \<List>, \<ListItemGroup>, and \<ListItem>
20
21![en-us_image_0000001562940589](figures/en-us_image_0000001562940589.png)
22
23>**NOTE**
24>
25>A **\<List>** component can contain only **\<ListItemGroup>** or **\<ListItem>** as its child components. **\<ListItemGroup>** and **\<ListItem>** must be used together with **\<List>**.
26
27
28### Layout
29
30Apart from the aforementioned features, the list is also able to adapt to the number of elements in the cross axis direction.
31
32When used in vertical layout, the list can contain one or more scrollable columns, as shown below.
33
34  **Figure 2** Vertical scrolling list (left: one column; right: multiple columns)
35
36![en-us_image_0000001511580940](figures/en-us_image_0000001511580940.png)
37
38When used in horizontal layout, the list can contain one or more scrollable rows, as shown below.
39
40  **Figure 3** Horizontal scrolling list (left: one column; right: multiple columns)
41
42![en-us_image_0000001511421344](figures/en-us_image_0000001511421344.png)
43
44
45### Constraints
46
47The main axis direction of a list refers to the direction in which the child component columns are laid out and in which the list scrolls. An axis perpendicular to the main axis is referred to as a cross axis, and the direction of the cross axis is perpendicular to a direction of the main axis.
48
49As shown below, the main axis of a vertical list is in the vertical direction, and the cross axis is in the horizontal direction. The main axis of a horizontal list is in the horizontal direction, and the cross axis is in the horizontal direction.
50
51  **Figure 4** Main axis and cross axis of the list
52
53![en-us_image_0000001562940581](figures/en-us_image_0000001562940581.png)
54
55If a size is set for the main axis or cross axis of the **\<List>** component, it is used as the size of the component in the corresponding direction.
56
57If no size is set for the main axis of the **\<List>** component, the size of the **\<List>** component in the main axis direction automatically adapts to the total size of its child components, as long as the total size of the child components in the main axis direction does not exceed the size of the parent component of **\<List>**.
58
59In the example shown below, no height is set for vertical list B, and the height of its parent component A is 200 vp. If the total height of all child components C is 150 vp, the height of list B is 150 vp.
60
61  **Figure 5** Main axis height constraint example 1 (A: parent component of \<List>; B: \<List> component; C: all child components of \<List>)
62
63![en-us_image_0000001511580956](figures/en-us_image_0000001511580956.png)
64
65If the total size of the child components in the main axis direction is greater than the size of the parent component of **\<List>**, the size of the **\<List>** component in the main axis direction automatically adapts to the size of its parent component.
66
67In the example shown below, still no height is set for vertical list B, and the height of its parent component A is 200 vp. If the total height of all child components C is 300 vp, the height of list B is 200 vp.
68
69  **Figure 6** Main axis height constraint example 2 (A: parent component of \<List>; B: \<List> component; C: all child components of \<List>)
70
71![en-us_image_0000001511740548](figures/en-us_image_0000001511740548.png)
72
73If no size is set for the cross axis of the **\<List>** component, the size of the **\<List>** component in the cross axis direction automatically adapts to the size of its parent component.
74
75
76## Developing the Layout
77
78
79### Setting the Main Axis Direction
80
81By default, the main axis of the **\<List>** component runs in the vertical direction. This means that you can create a vertical scrolling list without the need to manually set the list direction.
82
83To create a horizontal scrolling list, set the **listDirection** attribute to **Axis.Horizontal**. The default value of **listDirection** is **Axis.Vertical**.
84
85
86```ts
87List() {
88  ...
89}
90.listDirection(Axis.Horizontal)
91```
92
93
94### Setting the Cross Axis Layout
95
96The cross axis layout of the **\<List>** component can be set using the **lanes** and **alignListItem** attributes. The **lanes** attribute controls the number of list items along the cross axis, and the **alignListItem** attribute controls the alignment mode of child components along the cross axis.
97
98The lanes attribute of the **\<List>** component is useful in building a list that auto-adapts the numbers of rows or columns on devices of different sizes. Its value type is number or [LengthConstrain](../reference/arkui-ts/ts-types.md#lengthconstrain). If you are building a two-column vertical list shown on the right in Figure 2, set the **lanes** attribute to **2**. The default value of **lanes** is **1**.
99
100
101```ts
102List() {
103  ...
104}
105.lanes(2)
106```
107
108If set to a value of the LengthConstrain type, the **lanes** attribute determines the number of rows or columns based on the LengthConstrain settings and the size of the **\<List>** component.
109
110
111```ts
112List() {
113  ...
114}
115.lanes({ minLength: 200, maxLength: 300 })
116```
117
118For example, if the **lanes** attribute is set to **{ minLength: 200, maxLength: 300 }** for a vertical list, then:
119
120- When the list width is 300 vp, the list contains one column, because **minLength** is 200 vp.
121
122- When the list width changes to 400 vp, which is twice that of the **minLength** value, the list is automatically adapted to two-column.
123
124>**NOTE**
125>
126>When the **lanes** attribute is set to a value of the LengthConstrain type, the value is used only to calculate the number of rows or columns in the list and does not affect the size of the list items.
127
128With regard to a vertical list, when the **alignListItem** attribute is set to **ListItemAlign.Center**, list items are center-aligned horizontally; when the **alignListItem** attribute is at its default value **ListItemAlign.Start**, list items are aligned toward the start edge of the cross axis in the list.
129
130
131```ts
132List() {
133  ...
134}
135.alignListItem(ListItemAlign.Center)
136```
137
138
139## Displaying Data in the List
140
141The list displays a collection of items horizontally or vertically and can scroll to reveal content off the screen. In the simplest case, a **\<List>** component is statically made up of **\<ListItem>** components.
142
143  **Figure 7** Example of a city list
144
145![en-us_image_0000001563060761](figures/en-us_image_0000001563060761.png)
146
147```ts
148@Component
149struct CityList {
150  build() {
151    List() {
152      ListItem() {
153        Text('Beijing').fontSize(24)
154      }
155
156      ListItem() {
157        Text('Hangzhou').fontSize(24)
158      }
159
160      ListItem() {
161        Text('Shanghai').fontSize(24)
162      }
163    }
164    .backgroundColor('#FFF1F3F5')
165    .alignListItem(ListItemAlign.Center)
166  }
167}
168```
169
170Each **\<ListItem>** component can contain only one root child component. Therefore, it does not allow use of child components in tile mode. If tile mode is required, you need to encapsulate the child components into a container or create a custom component.
171
172  **Figure 8** Example of a contacts list
173
174![en-us_image_0000001511421328](figures/en-us_image_0000001511421328.png)
175
176As shown above, as a list item, each contact has a profile picture and a name. To present it, you can encapsulate **\<Image>** and **\<Text>** components into a **\<Row>** container.
177
178
179```ts
180List() {
181  ListItem() {
182    Row() {
183      Image($r('app.media.iconE'))
184        .width(40)
185        .height(40)
186        .margin(10)
187
188      Text ('Tom')
189        .fontSize(20)
190    }
191  }
192
193  ListItem() {
194    Row() {
195      Image($r('app.media.iconF'))
196        .width(40)
197        .height(40)
198        .margin(10)
199
200      Text ('Tracy')
201        .fontSize(20)
202    }
203  }
204}
205```
206
207
208## Iterating List Content
209
210Compared with a static list, a dynamic list is more common in applications. You can use [ForEach](../quick-start/arkts-rendering-control-foreach.md) to obtain data from the data source and create components for each data item.
211
212For example, when creating a contacts list, you can store the contact name and profile picture data in a **Contact** class structure to the **contacts** array, and nest **ListItem**s in **ForEach**, thereby reducing repeated code needed for tiling similar list items.
213
214
215```ts
216import util from '@ohos.util';
217
218class Contact {
219  key: string = util.generateRandomUUID(true);
220  name: string;
221  icon: Resource;
222
223  constructor(name: string, icon: Resource) {
224    this.name = name;
225    this.icon = icon;
226  }
227}
228
229@Entry
230@Component
231struct SimpleContacts {
232  private contacts = [
233    new Contact ('Tom', $r ("app.media.iconA")),
234    new Contact ('Tracy', $r ("app.media.iconB")),
235    ...
236  ]
237
238  build() {
239    List() {
240      ForEach(this.contacts, (item: Contact) => {
241        ListItem() {
242          Row() {
243            Image(item.icon)
244              .width(40)
245              .height(40)
246              .margin(10)
247            Text(item.name).fontSize(20)
248          }
249          .width('100%')
250          .justifyContent(FlexAlign.Start)
251        }
252      }, item => item.key)
253    }
254    .width('100%')
255  }
256}
257```
258
259In the **\<List>** component, **ForEach** can be used to render **\<ListItemGroup>** items as well as **\<ListItem>** items. For details, see [Adding Grouping Support](#adding-grouping-support).
260
261
262## Customizing the List Style
263
264
265### Setting the Spacing
266
267When initializing a list, you can use the **space** parameter to add spacing between list items. In the following example, a 10vp spacing is added between list items along the main axis:
268
269
270```ts
271List({ space: 10 }) {
272  ...
273}
274```
275
276
277### Adding Dividers
278
279A divider separates UI items to make them easier to identify. In the following figure, a divider is added between the setting items. Note that since the icons are easy to identify in their own right, the divers do not extend below the icons.
280
281  **Figure 9** Using dividers between the setting items
282
283![en-us_image_0000001511580960](figures/en-us_image_0000001511580960.png)
284
285To add dividers between items in a **\<List>** component, you can use its **divider** attribute, sprucing up the dividers with the following style attributes:<br> **strokeWidth** and **color**: indicate the stroke width and color of the diver, respectively.
286
287**startMargin** and **endMargin**: indicate the distance between the divider and the start edge and end edge of the list, respectively.
288
289
290```ts
291List() {
292  ...
293}
294.divider({
295  strokeWidth: 1,
296  startMargin: 60,
297  endMargin: 10,
298  color: '#ffe9f0f0'
299})
300```
301
302This example draws a divider with a stroke thickness of 1 vp from a position 60 vp away from the start edge of the list to a position 10 vp away from the end edge of the list. The effect is shown in Figure 8.
303
304>**NOTE**
305>
306>1. The stroke width of the divider causes some space between list items. If the content spacing set for the list is smaller than the stroke width of the divider, the latter is used instead.
307>
308>2. When a list contains multiple columns, the **startMargin** and **endMargin** attributes of the divider apply to each column.
309>
310>3. The divider is drawn between list items. No divider is drawn above the first list item and below the last list item.
311
312
313### Adding a Scrollbar
314
315When the total height (width) of list items exceeds the screen height (width), the list can scroll vertically (horizontally). The scrollbar of a list enables users to quickly navigate the list content, as shown below.
316
317  **Figure 10** Scrollbar of a list
318
319![en-us_image_0000001511740544](figures/en-us_image_0000001511740544.gif)
320
321When using the **\<List>** component, you can use the **scrollBar** attribute to control the display of the list scrollbar. The value type of **scrollBar** is [BarState](../reference/arkui-ts/ts-appendix-enums.md#barstate). When the value is **BarState.Auto**, the scrollbar is displayed as required: It is displayed when the scrollbar area is touched and becomes thicker when being dragged; it automatically disappears after 2 seconds of inactivity.
322
323
324```ts
325List() {
326  ...
327}
328.scrollBar(BarState.Auto)
329```
330
331
332## Adding Grouping Support
333
334By allowing data to be displayed in groups in the list, you make the list easier to scan and navigate. Grouping is common in real-world applications. For example, the contacts list below use grouping.
335
336  **Figure 11** Contacts list with grouping
337
338![en-us_image_0000001511580948](figures/en-us_image_0000001511580948.png)
339
340You can use **\<ListItemGroup>** to group items in the **\<List>** component to build a two-dimensional list.
341
342A **\<List>** component allows one or more **\<ListItemGroup>** child components. By default, the width of **\<ListItemGroup>** is equal to that of **\<List>**. When initializing **\<ListItemGroup>**, you can use the **header** parameter to set its header.
343
344
345```ts
346@Component
347struct ContactsList {
348  ...
349
350  @Builder itemHead(text: string) {
351    // Header of the list group, corresponding to the group A and B locations.
352    Text(text)
353      .fontSize(20)
354      .backgroundColor('#fff1f3f5')
355      .width('100%')
356      .padding(5)
357  }
358
359  build() {
360    List() {
361      ListItemGroup({ header: this.itemHead('A') }) {
362        // Render the repeated list items of group A.
363        ...
364      }
365      ...
366
367      ListItemGroup({ header: this.itemHead('B') }) {
368        // Render the repeated list items of group B.
369        ...
370      }
371      ...
372    }
373  }
374}
375```
376
377If the structures of multiple **\<ListItemGroup>** components are similar, you can combine the data of these components into an array and use **ForEach** to render them cyclically. For example, in the contacts list, the **contacts** data of each group (for details, see [Iterating List Content](#iterating-list-content)) and the **title** data of the corresponding group are combined and defined as the **contactsGroups** array.
378
379
380```ts
381contactsGroups: object[] = [
382  {
383    title: 'A',
384    contacts: [
385      new Contact('Alice', $r('app.media.iconA')),
386      new Contact ('Ann', $r ('app.media.iconB')),
387      new Contact('Angela', $r('app.media.iconC')),
388    ],
389  },
390  {
391    title: 'B',
392    contacts: [
393      new Contact ('Ben', $r ('app.media.iconD')),
394      new Contact ('Bryan', $r ('app.media.iconE')),
395    ],
396  },
397  ...
398]
399```
400
401Then, with rendering of **contactsGroups** in **ForEach**, a contact list with multiple groups is implemented.
402
403
404```ts
405List() {
406  // Render the <ListItemGroup> components cyclically. contactsGroups is the data set of contacts and titles of multiple groups.
407  ForEach(this.contactsGroups, item => {
408    ListItemGroup({ header: this.itemHead(item.title) }) {
409      // Render <ListItem> components cyclically.
410      ForEach(item.contacts, (contact) => {
411        ListItem() {
412          ...
413        }
414      }, item => item.key)
415    }
416    ...
417  })
418}
419```
420
421
422## Adding a Sticky Header
423
424The sticky header is a common pattern for keeping the header in the same place on the screen while the user scrolls down the list. As shown in the following figure, when you scroll through group A in the contacts list, the header of group B is always below group A. When you start scrolling through group B, the header of group B is fixed at the top of the screen. After group B has been scrolled to the bottom, the header of group B is replaced by the header of next group.
425
426Sticky headers not only signify the representation and usage of data in the respective groups, but also help users navigate through a large amount of information, thereby avoiding unnecessary scrolling between the top of the area where the header is located and the area of interest.
427
428  **Figure 12** Sticky header
429
430![en-us_image_0000001511740552](figures/en-us_image_0000001511740552.gif)
431
432You can set a sticky header or footer for a **\<ListItemGroup>** component by setting the **sticky** attribute of its parent **\<List>** component.
433
434Setting the **sticky** attribute to **StickyStyle.Header** implements a sticky header. To implement a sticky footer, use the **footer** parameter to initialize the footer of **\<ListItemGroup>** and set the **sticky** attribute to **StickyStyle.Footer**.
435
436
437```ts
438@Component
439struct ContactsList {
440  // Define the contactsGroups array.
441  ...
442
443  @Builder itemHead(text: string) {
444    // Header of the list group, corresponding to the group A and B locations.
445    Text(text)
446      .fontSize(20)
447      .backgroundColor('#fff1f3f5')
448      .width('100%')
449      .padding(5)
450  }
451
452  build() {
453    List() {
454      // Render the <ListItemGroup> components cyclically. contactsGroups is the data set of contacts and titles of multiple groups.
455      ForEach(this.contactsGroups, item => {
456        ListItemGroup({ header: this.itemHead(item.title) }) {
457          // Render <ListItem> components cyclically.
458          ForEach(item.contacts, (contact) => {
459            ListItem() {
460              ...
461            }
462          }, item => item.key)
463        }
464        ...
465      })
466    }
467    .sticky(StickyStyle.Header) // Set a sticky header.
468  }
469}
470```
471
472
473## Controlling the Scrolling Position
474
475In some cases you may want to control the scrolling position of a list. For example, when there are a huge number of items in the news page list, you may want to allow users to quickly jump to the top or bottom of the list after they have scrolled to a certain point. Below is an example.
476
477  **Figure 13** Returning to the top of the list
478
479![en-us_image_0000001511900520](figures/en-us_image_0000001511900520.gif)
480
481When the **\<List>** component is initialized, you can use the **scroller** parameter to bind a [Scroller](../reference/arkui-ts/ts-container-scroll.md#scroller) object to control the scrolling of the list. In this example of a news page list, the **scrollToIndex** API of the **Scroller** object is used to scroll the list to the list item with the specified index. This allows the user to return to the top of the list by clicking a specific button.
482
483First, you need to create a **Scroller** object **listScroller**.
484
485
486```ts
487private listScroller: Scroller = new Scroller();
488```
489
490Then, use **listScroller** to initialize the **scroller** parameter to bind it with the **\<List>** component. Set **scrollToIndex** to **0**, meaning to return to the top of the list.
491
492
493```ts
494Stack({ alignContent: Alignment.BottomEnd }) {
495  // use listScroller to initialize the scroller parameter to bind it with the <List> component.
496  List({ space: 20, scroller: this.listScroller }) {
497    ...
498  }
499  ...
500
501  Button() {
502    ...
503  }
504  .onClick(() => {
505    // Specify where e to jump when the specific button is clicked, which is the top of the list in this example.
506    this.listScroller.scrollToIndex(0)
507  })
508  ...
509}
510```
511
512
513## Responding to the Scrolling Position
514
515Many applications need to listen for the scrolling position change of the list and respond. For example, with regard to a contacts list, if scrolling spans more than one group, the alphabetical index bar at one side of the list also needs to be updated to highlight the letter corresponding to the current group.
516
517Another common example is a scrolling list working with a multi-level index bar, as in the case of a product category page in a shopping application.
518
519**Figure 14** Alphabetical index bar's response to contacts list scrolling
520
521![en-us_image_0000001563060769](figures/en-us_image_0000001563060769.gif)
522
523As shown above, when the contacts list scrolls from group A to B, the alphabetical index bar on the right also changes from A to B. This scenario can be implemented by listening for the **onScrollIndex** event of the **\<List>** component. The alphabet index bar is implemented using the [\<AlphabetIndexer>](../reference/arkui-ts/ts-container-alphabet-indexer.md) component.
524
525When the list scrolls, the **selectedIndex** value of the letter to highlight in the alphabet index bar is recalculated based on the **firstIndex** value of the item to which the list has scrolled. In the **\<AlphabetIndexer>** component, the index of the highlighted item is set through the **selected** attribute. When the value of **selectedIndex** changes, the **\<AlphabetIndexer>** component is re-rendered to highlight the corresponding letter.
526
527
528```ts
529...
530const alphabets = ['#', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
531  'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
532
533@Entry
534@Component
535struct ContactsList {
536  @State selectedIndex: number = 0;
537  private listScroller: Scroller = new Scroller();
538  ...
539
540  build() {
541    Stack({ alignContent: Alignment.End }) {
542      List({ scroller: this.listScroller }) {
543        ...
544      }
545      .onScrollIndex((firstIndex: number) => {
546        // Recalculate the value of this.selectedIndex in the alphabetical index bar based on the index of the item to which the list has scrolled.
547        ...
548      })
549      ...
550
551      // <AlphabetIndexer> component
552      AlphabetIndexer({ arrayValue: alphabets, selected: 0 })
553        .selected(this.selectedIndex)
554      ...
555    }
556  }
557}
558```
559
560>**NOTE**
561>
562>During index calculation, each **\<ListItemGroup>** component is taken as a whole and assigned an index, and the indexes of the list items within are not included in the calculation.
563
564
565## Responding to Swipe on List Items
566
567Swipe menus are common in many applications. For example, a messaging application generally provides a swipe-to-delete feature for its message list. This feature allows users to delete a message by swiping left on it in the list and touching the delete button, as shown in the following figure.
568
569**Figure 15** Swipe-to-delete feature
570
571![en-us_image_0000001563060773](figures/en-us_image_0000001563060773.gif)
572
573To implement the swipe feature, you can use the **swipeAction** attribute of **\<ListItem>**. In initialization of the **swipeAction** attribute, the **SwipeActionOptions** parameter is mandatory, wherein the **start** parameter indicates the component that appears from the start edge when the list item slides right, and the **end** parameter indicates the component that appears from the end edge when the list item slides left.
574
575In the example of the message list, the **end** parameter is set to a custom delete button. In initialization of the **end** attribute, the index of the sliding list item is passed to the delete button. When the user touches the delete button, the data corresponding to the list item is deleted based on the index.
576
577
578```ts
579@Entry
580@Component
581struct MessageList {
582  @State messages: object[] = [
583    // Initialize the message list data.
584    ...
585  ];
586
587  @Builder itemEnd(index: number) {
588    // Set the component that appears from the end edge when the list item slides left.
589    Button({ type: ButtonType.Circle }) {
590      Image($r('app.media.ic_public_delete_filled'))
591        .width(20)
592        .height(20)
593    }
594    .onClick(() => {
595      this.messages.splice(index, 1);
596    })
597    ...
598  }
599
600  build() {
601    ...
602      List() {
603        ForEach(this.messages, (item, index) => {
604          ListItem() {
605            ...
606          }
607          .swipeAction({ end: this.itemEnd.bind(this, index) }) // Set the swipe attributes.
608        }, item => item.id.toString())
609      }
610    ...
611  }
612}
613```
614
615
616## Adding a Mark to a List Item
617
618A mark is an intuitive, unintrusive visual indicator to draw attention and convey a specific message. For example, when a new message is received in the message list, a mark is displayed in the upper right corner of the contact's profile picture, indicating that there is a new message from that contact, as shown in the following figure.
619
620  **Figure 16** Adding a mark to a list item
621
622![en-us_image_0000001511580952](figures/en-us_image_0000001511580952.png)
623
624To add a mark, you can use the [\<Badge>](../reference/arkui-ts/ts-container-badge.md) component in **\<ListItem>**. The **\<Badge>** component is a container that can be attached to another component for tagging.
625
626In this example, when implementing the **\<Image>** component for presenting the profile picture of a list item, add it to **\<Badge>** as a child component.
627
628In the **\<Badge>** component, the **count** and **position** parameters are used to set the number of notifications and the position to display the badge, respectively. You can also use the **style** parameter to spruce up the mark.
629
630
631```ts
632Badge({
633  count: 1,
634  position: BadgePosition.RightTop,
635  style: { badgeSize: 16, badgeColor: '#FA2A2D' }
636}) {
637  // The <Image> component implements the contact profile picture.
638  ...
639}
640...
641```
642
643
644## Implementing Pull-Down-to-Refresh and Pull-Up-to-Load
645
646The pull-down-to-refresh and pull-up-to-load features are widely used in mobile applications, such as news applications. In effect, the implementation of these two features follows the same process: (1) As response to a [touch event](../reference/arkui-ts/ts-universal-events-touch.md), a refresh or load view is displayed at the top or bottom of the page; (2) when the refresh or load is complete, the refresh or load view is hidden.
647
648The following describes the implementation of the pull-and-refresh feature:
649
6501. Listen for the finger press event and record the value of the initial position.
651
6522. Listen for the finger movement event, and record and calculate the difference between the value of the current position and the initial value. If the difference is greater than 0, the finger moves downward. Set the maximum value for the movement.
653
6543. Listen for the finger lift event. If the movement reaches the maximum value, trigger data loading and display the refresh view. After the loading is complete, hide the view.
655
656 You can also use the third-party component [PullToRefresh](https://gitee.com/openharmony-sig/PullToRefresh) to implement this feature.
657
658
659## Editing a List
660
661The list editing mode is frequently used in various scenarios, such as to-do list management, file management, and note management. In editing mode, adding and deleting list items are the most basic functions. The core is to add and delete data in the data set corresponding to the list items.
662
663The following uses to-do list management as an example to describe how to quickly add and delete list items.
664
665
666### Adding a List Item
667
668As shown below, when a user touches **Add**, a page is displayed for the user to set options for the new list item. After the user touches **OK**, the corresponding item is added to the list.
669
670  **Figure 17** Adding a to-do task
671
672![en-us_image_0000001511740556](figures/en-us_image_0000001511740556.gif)
673
674The process of implementing the addition feature is as follows:
675
6761. Define the list item data structure and initialize the list data to build the overall list layout and list items.
677   In this example, first define the to-do data structure.
678
679   ```ts
680   import util from '@ohos.util';
681
682   export class ToDo {
683     key: string = util.generateRandomUUID(true);
684     name: string;
685
686     constructor(name: string) {
687       this.name = name;
688     }
689   }
690   ```
691
692    Then, initialize the to-do list data and options:
693
694   ```ts
695   @State toDoData: ToDo[] = [];
696   private availableThings: string[] = ['Reading', 'Fitness', 'Travel','Music','Movie', 'Singing'];
697   ```
698
699   Finally, build the list layout and list items:
700
701   ```ts
702   List({ space: 10 }) {
703     ForEach(this.toDoData, (toDoItem) => {
704       ListItem() {
705         ...
706       }
707     }, toDoItem => toDoItem.key)
708   }
709   ```
710
7112. Provide the entry for adding a list item, that is, add a click event to the add button.
712
7133. Respond to the user's confirmation of adding and update the list data.
714   The code snippet for steps 2 and 3 is as follows:
715
716   ```ts
717   Text('+')
718     .onClick(() => {
719       TextPickerDialog.show({
720         range: this.availableThings,
721         onAccept: (value: TextPickerResult) => {
722            this.toDoData.push(new ToDo(this.availableThings[value.index])); // Add the list item data.
723         },
724       })
725     })
726   ```
727
728
729### Deleting a List Item
730
731As shown below, when the user long presses a list item to enter the deletion mode, a page is displayed for the user to delete the list item. After the user selects the list item and touches the delete button, the list item is deleted.
732
733  **Figure 18** Deleting a to-do task
734
735![en-us_image_0000001562820877](figures/en-us_image_0000001562820877.gif)
736
737The process of implementing the deletion feature is as follows:
738
7391. Generally, the deletion feature is available only after the list enters the editing mode. Therefore, the entry to the editing mode needs to be provided.
740   In this example, by listening for the long press event of a list item, the list enters the editing mode when the user long presses a list item.
741
742   ```ts
743   // ToDoListItem.ets
744
745   Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
746     ...
747   }
748   .gesture(
749   GestureGroup(GestureMode.Exclusive,
750     LongPressGesture()
751       .onAction(() => {
752         if (!this.isEditMode) {
753           this.isEditMode = true; // Enter the editing mode.
754           this.selectedItems.push(this.toDoItem); // Record the list item selected when the user long presses the button.
755         }
756       })
757     )
758   )
759   ```
760
7612. Respond to the selection by the user and record the list items to be deleted.
762   In this example of the to-do list, respond to the selection by correctly displaying the check mark and record all the selected list items.
763
764   ```ts
765   // ToDoListItem.ets
766
767   if (this.isEditMode) {
768     Checkbox()
769       .onChange((isSelected) => {
770         if (isSelected) {
771           this.selectedItems.push(this.toDoItem) // When an item is selected, record the selected item.
772         } else {
773           let index = this.selectedItems.indexOf(this.toDoItem)
774           if (index !== -1) {
775             this.selectedItems.splice(index, 1) // When an item is deselected, delete the item from the selectedItems array.
776           }
777         }
778       })
779       ...
780   }
781   ```
782
7833. Respond to the user's clicking the delete button and delete the corresponding items from the list.
784
785   ```ts
786   // ToDoList.ets
787
788   Button ('Delete')
789     .onClick(() => {
790       // Delete the toDoData data corresponding to the selected list items.
791       let leftData = this.toDoData.filter((item) => {
792         return this.selectedItems.find((selectedItem) => selectedItem !== item);
793       })
794
795       this.toDoData = leftData;
796       this.isEditMode = false;
797     })
798     ...
799   ```
800
801
802## Handling a Long List
803
804[ForEach](../quick-start/arkts-rendering-control-foreach.md) is applicable to short lists. With regard to a long list with a large number of list items, using **ForEach** will greatly slow down page loading, as it loads all list items at a time. Therefore, for better list performance, use [LazyForEach](../quick-start/arkts-rendering-control-lazyforeach.md) instead to implement on-demand iterative data loading.
805
806For details about the implementation, see the example in [LazyForEach: Lazy Data Loading](../quick-start/arkts-rendering-control-lazyforeach.md).
807
808When the list is rendered in lazy loading mode, to improve the list scrolling experience and minimize white blocks during list scrolling, you can use the **cachedCount** parameter of the **\<List>** component. This parameter sets the number of list items preloaded outside of the screen and is valid only in **LazyForEach**.
809
810
811```ts
812List() {
813  LazyForEach(this.dataSource, item => {
814    ListItem() {
815      ...
816    }
817  })
818}.cachedCount(3)
819```
820
821The following uses a vertical list as an example:
822
823- If lazy loading is used for list items and the list contains only one column, the number of the list items to cache before and after the currently displayed one equals the value of **cachedCount**. If the list contains multiple columns, the number of the list items to cache is the value of **cachedCount** multiplied by the number of columns.
824
825- If lazy loading is used for list item groups, the number of the list item groups to cache before and after the currently displayed one equals the value of **cachedCount**, regardless of the number of columns.
826
827>**NOTE**
828>
829>1. A greater **cachedCount** value may result in higher CPU and memory overhead of the UI. Adjust the value by taking into account both the comprehensive performance and user experience.
830>
831>2. When a list uses data lazy loading, all list items except the list items in the display area and the cached list items are destroyed.
832
833