> 💫 **坚果派·红目香薰** 倾情分享  

> 🎯 用心打造每一个技术细节,为开发者创造更多价值  

> 📱 让HarmonyOS开发变得更简单、更有趣

 

---

 

## ✨ 写在前面的话

 

嗨,亲爱的技术朋友们!👋

 

我是来自坚果派的红目香薰,一个热爱技术、专注HarmonyOS开发的程序媛。在这个数字化飞速发展的时代,HarmonyOS作为华为自主研发的操作系统,正在改变着我们的数字生活体验。

 

🌈 **为什么要写这个系列?**

- 💡 让复杂的技术变得简单易懂

- 🚀 帮助更多开发者快速上手HarmonyOS

- 💝 分享实战经验,避免踩坑

- 🌟 用代码创造美好,用技术传递温暖

 

每一个Demo都是我精心设计和反复测试的结果,希望能够为你的HarmonyOS开发之路点亮一盏明灯。✨

 

今天我们来深入学习HarmonyOS中最常用的容器组件之一——List列表组件。从基础列表到复杂的交互列表,让我们一起打造流畅优雅的列表体验!

 

---

 

## 📋 Demo功能说明

### 🎯 核心功能

本Demo展示了HarmonyOS中List组件的全面使用方法,包括:

- 📝 基础垂直列表和水平列表

- 🎨 自定义列表项样式和布局

- 🔄 下拉刷新和上拉加载更多

- 🗂️ 分组列表和粘性标题

- 🎯 列表项的增删改操作

- 🔍 搜索过滤功能

- 💫 滑动删除和拖拽排序

- 📱 多选模式和批量操作

 

### ✨ 特色亮点

- 🎨 **视觉精美**:多种列表样式和动画效果

- 🚀 **性能优化**:使用LazyForEach实现大数据列表

- 📱 **交互丰富**:支持多种手势操作和状态管理

- 💡 **实用性强**:涵盖实际开发中的各种列表场景

- 🌟 **代码优雅**:模块化设计,易于维护和扩展

 

### 🎨 界面展示

界面采用多标签页设计,展示不同类型的列表:

- 基础列表:简单文本列表和图文列表

- 样式列表:卡片式、圆角、阴影效果

- 交互列表:可点击、滑动删除、拖拽排序

- 分组列表:带标题的分组展示

- 动态列表:增删改查和搜索功能

 

### 📱 适用场景

- 📰 新闻资讯类应用的文章列表

- 💬 聊天应用的消息列表

- 🛍️ 电商应用的商品列表

- 📞 通讯录和联系人列表

- 📁 文件管理器的文件列表

- ⚙️ 设置页面的选项列表

 

---

 

## 🔧 核心代码说明

 

### 📁 项目结构

```

ListDemo/

├── src/

│   ├── main/

│   │   ├── ets/

│   │   │   ├── pages/

│   │   │   │   └── Index.ets          // 主页面

│   │   │   └── entryability/

│   │   └── resources/

│   │       ├── base/

│   │       │   ├── element/

│   │       │   └── media/

│   │       └── rawfile/

│   └── module.json5

```

 

### 🎯 关键技术点

 

#### 1. List组件基础结构

```typescript

List({ space: 10 }) {

  ForEach(this.dataList, (item: DataItem) => {

    ListItem() {

      // 列表项内容

    }

  })

}

.width('100%')

.height('100%')

```

 

#### 2. LazyForEach性能优化

```typescript

List() {

  LazyForEach(this.dataSource, (item: DataItem) => {

    ListItem() {

      // 列表项内容

    }

  })

}

```

 

#### 3. 列表项交互

- **onClick**: 点击事件

- **onSwipeAction**: 滑动操作

- **onMove**: 拖拽移动

- **onSelect**: 选择状态

 

#### 4. 列表滚动控制

- **scrollTo**: 滚动到指定位置

- **scrollBy**: 相对滚动

- **onScroll**: 滚动监听

- **onReachStart/End**: 到达边界监听

 

### 💡 技术要点解析

 

**LazyForEach优化**:

对于大量数据的列表,使用LazyForEach可以实现按需加载,提升性能。

 

**滑动删除实现**:

通过swipeAction属性可以为列表项添加滑动操作,实现删除、编辑等功能。

 

**分组列表设计**:

使用sticky属性可以实现粘性标题效果,提升用户体验。

 

---

 

## 📝 完整Demo代码

 

### 🏠 主页面代码

```typescript

// src/main/ets/pages/Index.ets

 

// 数据模型

interface ContactItem {

  id: number

  name: string

  phone: string

  avatar: string

  group: string

}

 

interface NewsItem {

  id: number

  title: string

  content: string

  time: string

  image: string

  category: string

}

 

interface TodoItem {

  id: number

  title: string

  completed: boolean

  priority: string

}

 

@Entry

@Component

struct Index {

  @State currentTab: number = 0

  @State searchText: string = ''

  @State isMultiSelect: boolean = false

  @State selectedItems: Set<number> = new Set()

 

  // 联系人数据

  @State contactList: ContactItem[] = [

    { id: 1, name: '张三', phone: '138****1234', avatar: '👨', group: 'A' },

    { id: 2, name: '李四', phone: '139****5678', avatar: '👩', group: 'L' },

    { id: 3, name: '王五', phone: '136****9012', avatar: '👨', group: 'W' },

    { id: 4, name: '赵六', phone: '137****3456', avatar: '👩', group: 'Z' },

    { id: 5, name: '陈七', phone: '135****7890', avatar: '👨', group: 'C' },

    { id: 6, name: '刘八', phone: '134****2345', avatar: '👩', group: 'L' },

  ]

 

  // 新闻数据

  @State newsList: NewsItem[] = [

    { id: 1, title: 'HarmonyOS 4.0正式发布', content: '华为发布全新操作系统...', time: '2小时前', image: '📱', category: '科技' },

    { id: 2, title: '人工智能技术新突破', content: 'AI技术在各领域应用...', time: '4小时前', image: '🤖', category: '科技' },

    { id: 3, title: '绿色出行新理念', content: '环保出行方式推广...', time: '6小时前', image: '🌱', category: '生活' },

    { id: 4, title: '健康饮食新趋势', content: '营养搭配科学指南...', time: '8小时前', image: '🥗', category: '健康' },

    { id: 5, title: '教育改革新政策', content: '教育部发布最新政策...', time: '10小时前', image: '📚', category: '教育' },

  ]

 

  // 待办事项数据

  @State todoList: TodoItem[] = [

    { id: 1, title: '完成HarmonyOS项目开发', completed: false, priority: 'high' },

    { id: 2, title: '准备技术分享PPT', completed: true, priority: 'medium' },

    { id: 3, title: '学习ArkTS新特性', completed: false, priority: 'high' },

    { id: 4, title: '整理代码文档', completed: false, priority: 'low' },

    { id: 5, title: '参加团队会议', completed: true, priority: 'medium' },

  ]

 

  build() {

    Column() {

      // 标题区域

      this.buildTitleSection()

     

      // 标签页

      this.buildTabSection()

     

      // 内容区域

      if (this.currentTab === 0) {

        this.buildContactList()

      } else if (this.currentTab === 1) {

        this.buildNewsList()

      } else if (this.currentTab === 2) {

        this.buildTodoList()

      } else {

        this.buildCustomList()

      }

    }

    .width('100%')

    .height('100%')

    .backgroundColor('#F5F5F5')

  }

 

  // 标题区域

  @Builder

  buildTitleSection() {

    Column({ space: 10 }) {

      Text('📋 HarmonyOS List列表组件')

        .fontSize(24)

        .fontWeight(FontWeight.Bold)

        .fontColor(Color.White)

        .textAlign(TextAlign.Center)

        .width('100%')

        .padding(20)

        .borderRadius(15)

        .linearGradient({

          angle: 45,

          colors: [['#667eea', 0.0], ['#764ba2', 1.0]]

        })

        .shadow({

          radius: 10,

          color: '#40000000',

          offsetX: 0,

          offsetY: 5

        })

 

      Text('打造流畅优雅的列表体验')

        .fontSize(14)

        .fontColor('#666666')

        .textAlign(TextAlign.Center)

        .fontStyle(FontStyle.Italic)

    }

    .width('100%')

    .backgroundColor(Color.White)

    .padding(20)

    .borderRadius(12)

    .margin({ bottom: 10 })

    .shadow({

      radius: 8,

      color: '#20000000',

      offsetX: 0,

      offsetY: 2

    })

  }

 

  // 标签页

  @Builder

  buildTabSection() {

    Row({ space: 5 }) {

      Button('联系人')

        .width(70)

        .height(35)

        .fontSize(12)

        .backgroundColor(this.currentTab === 0 ? '#3498DB' : '#ECF0F1')

        .fontColor(this.currentTab === 0 ? Color.White : '#7F8C8D')

        .borderRadius(8)

        .onClick(() => {

          this.currentTab = 0

          this.resetSelection()

        })

 

      Button('新闻')

        .width(70)

        .height(35)

        .fontSize(12)

        .backgroundColor(this.currentTab === 1 ? '#3498DB' : '#ECF0F1')

        .fontColor(this.currentTab === 1 ? Color.White : '#7F8C8D')

        .borderRadius(8)

        .onClick(() => {

          this.currentTab = 1

          this.resetSelection()

        })

 

      Button('待办')

        .width(70)

        .height(35)

        .fontSize(12)

        .backgroundColor(this.currentTab === 2 ? '#3498DB' : '#ECF0F1')

        .fontColor(this.currentTab === 2 ? Color.White : '#7F8C8D')

        .borderRadius(8)

        .onClick(() => {

          this.currentTab = 2

          this.resetSelection()

        })

 

      Button('自定义')

        .width(70)

        .height(35)

        .fontSize(12)

        .backgroundColor(this.currentTab === 3 ? '#3498DB' : '#ECF0F1')

        .fontColor(this.currentTab === 3 ? Color.White : '#7F8C8D')

        .borderRadius(8)

        .onClick(() => {

          this.currentTab = 3

          this.resetSelection()

        })

    }

    .width('100%')

    .justifyContent(FlexAlign.SpaceEvenly)

    .padding({ left: 20, right: 20, bottom: 10 })

  }

 

  // 联系人列表

  @Builder

  buildContactList() {

    Column() {

      // 搜索框

      Row({ space: 10 }) {

        TextInput({ placeholder: '搜索联系人...' })

          .layoutWeight(1)

          .height(40)

          .fontSize(14)

          .backgroundColor('#F8F9FA')

          .borderRadius(20)

          .padding({ left: 15, right: 15 })

          .onChange((value: string) => {

            this.searchText = value

          })

 

        Button(this.isMultiSelect ? '取消' : '选择')

          .width(60)

          .height(40)

          .fontSize(12)

          .backgroundColor(this.isMultiSelect ? '#E74C3C' : '#3498DB')

          .borderRadius(20)

          .onClick(() => {

            this.isMultiSelect = !this.isMultiSelect

            if (!this.isMultiSelect) {

              this.selectedItems.clear()

            }

          })

      }

      .width('100%')

      .padding({ left: 20, right: 20, bottom: 10 })

 

      // 联系人列表

      List({ space: 1 }) {

        ForEach(this.getFilteredContacts(), (contact: ContactItem, index: number) => {

          ListItem() {

            Row({ space: 15 }) {

              // 多选框

              if (this.isMultiSelect) {

                Checkbox()

                  .select(this.selectedItems.has(contact.id))

                  .onChange((value: boolean) => {

                    if (value) {

                      this.selectedItems.add(contact.id)

                    } else {

                      this.selectedItems.delete(contact.id)

                    }

                  })

              }

 

              // 头像

              Text(contact.avatar)

                .fontSize(24)

                .width(50)

                .height(50)

                .textAlign(TextAlign.Center)

                .backgroundColor('#E8F4FD')

                .borderRadius(25)

 

              // 联系人信息

              Column({ space: 5 }) {

                Text(contact.name)

                  .fontSize(16)

                  .fontWeight(FontWeight.Medium)

                  .fontColor('#333333')

 

                Text(contact.phone)

                  .fontSize(14)

                  .fontColor('#666666')

              }

              .alignItems(HorizontalAlign.Start)

              .layoutWeight(1)

 

              // 操作按钮

              if (!this.isMultiSelect) {

                Button('📞')

                  .width(40)

                  .height(40)

                  .fontSize(16)

                  .backgroundColor('#4CAF50')

                  .borderRadius(20)

                  .onClick(() => {

                    console.log(`拨打电话: ${contact.phone}`)

                  })

              }

            }

            .width('100%')

            .padding(15)

            .backgroundColor(Color.White)

            .borderRadius(12)

            .shadow({

              radius: 5,

              color: '#10000000',

              offsetX: 0,

              offsetY: 2

            })

          }

          .onClick(() => {

            if (!this.isMultiSelect) {

              console.log(`点击联系人: ${contact.name}`)

            }

          })

          .swipeAction({

            end: this.buildSwipeActions(contact.id, 'contact')

          })

        })

      }

      .layoutWeight(1)

      .padding({ left: 20, right: 20 })

 

      // 批量操作按钮

      if (this.isMultiSelect && this.selectedItems.size > 0) {

        Row({ space: 15 }) {

          Button(`删除 (${this.selectedItems.size})`)

            .height(40)

            .fontSize(14)

            .backgroundColor('#E74C3C')

            .borderRadius(20)

            .onClick(() => {

              this.deleteSelectedContacts()

            })

 

          Button(`导出 (${this.selectedItems.size})`)

            .height(40)

            .fontSize(14)

            .backgroundColor('#27AE60')

            .borderRadius(20)

            .onClick(() => {

              console.log('导出选中联系人')

            })

        }

        .width('100%')

        .justifyContent(FlexAlign.Center)

        .padding(20)

        .backgroundColor(Color.White)

      }

    }

    .layoutWeight(1)

  }

 

  // 新闻列表

  @Builder

  buildNewsList() {

    List({ space: 10 }) {

      ForEach(this.newsList, (news: NewsItem) => {

        ListItem() {

          Row({ space: 15 }) {

            // 新闻图片

            Text(news.image)

              .fontSize(32)

              .width(60)

              .height(60)

              .textAlign(TextAlign.Center)

              .backgroundColor('#F0F0F0')

              .borderRadius(8)

 

            // 新闻内容

            Column({ space: 8 }) {

              Text(news.title)

                .fontSize(16)

                .fontWeight(FontWeight.Medium)

                .fontColor('#333333')

                .maxLines(2)

                .textOverflow({ overflow: TextOverflow.Ellipsis })

 

              Text(news.content)

                .fontSize(14)

                .fontColor('#666666')

                .maxLines(2)

                .textOverflow({ overflow: TextOverflow.Ellipsis })

 

              Row({ space: 10 }) {

                Text(news.category)

                  .fontSize(12)

                  .fontColor('#3498DB')

                  .padding({ left: 8, right: 8, top: 2, bottom: 2 })

                  .backgroundColor('#E8F4FD')

                  .borderRadius(10)

 

                Text(news.time)

                  .fontSize(12)

                  .fontColor('#999999')

                  .layoutWeight(1)

              }

              .width('100%')

            }

            .alignItems(HorizontalAlign.Start)

            .layoutWeight(1)

          }

          .width('100%')

          .padding(15)

          .backgroundColor(Color.White)

          .borderRadius(12)

          .shadow({

            radius: 5,

            color: '#10000000',

            offsetX: 0,

            offsetY: 2

          })

        }

        .onClick(() => {

          console.log(`阅读新闻: ${news.title}`)

        })

        .swipeAction({

          end: this.buildSwipeActions(news.id, 'news')

        })

      })

    }

    .layoutWeight(1)

    .padding({ left: 20, right: 20 })

  }

 

  // 待办列表

  @Builder

  buildTodoList() {

    Column() {

      // 添加按钮

      Row() {

        Button('➕ 添加待办')

          .height(40)

          .fontSize(14)

          .backgroundColor('#27AE60')

          .borderRadius(20)

          .onClick(() => {

            this.addTodoItem()

          })

      }

      .width('100%')

      .justifyContent(FlexAlign.Center)

      .padding({ left: 20, right: 20, bottom: 10 })

 

      // 待办列表

      List({ space: 8 }) {

        ForEach(this.todoList, (todo: TodoItem) => {

          ListItem() {

            Row({ space: 15 }) {

              // 完成状态

              Checkbox()

                .select(todo.completed)

                .onChange((value: boolean) => {

                  this.updateTodoStatus(todo.id, value)

                })

 

              // 待办内容

              Column({ space: 5 }) {

                Text(todo.title)

                  .fontSize(16)

                  .fontColor(todo.completed ? '#999999' : '#333333')

                  .decoration({

                    type: todo.completed ? TextDecorationType.LineThrough : TextDecorationType.None

                  })

 

                Text(this.getPriorityText(todo.priority))

                  .fontSize(12)

                  .fontColor(this.getPriorityColor(todo.priority))

                  .padding({ left: 6, right: 6, top: 2, bottom: 2 })

                  .backgroundColor(this.getPriorityBgColor(todo.priority))

                  .borderRadius(8)

              }

              .alignItems(HorizontalAlign.Start)

              .layoutWeight(1)

 

              // 优先级指示器

              Text(this.getPriorityIcon(todo.priority))

                .fontSize(16)

            }

            .width('100%')

            .padding(15)

            .backgroundColor(Color.White)

            .borderRadius(12)

            .shadow({

              radius: 5,

              color: '#10000000',

              offsetX: 0,

              offsetY: 2

            })

          }

          .swipeAction({

            end: this.buildSwipeActions(todo.id, 'todo')

          })

        })

      }

      .layoutWeight(1)

      .padding({ left: 20, right: 20 })

    }

    .layoutWeight(1)

  }

 

  // 自定义列表

  @Builder

  buildCustomList() {

    List({ space: 15 }) {

      // 卡片式列表项

      ListItem() {

        Column({ space: 10 }) {

          Text('🎨 卡片式列表项')

            .fontSize(18)

            .fontWeight(FontWeight.Bold)

            .fontColor('#333333')

 

          Text('这是一个自定义的卡片式列表项,展示了丰富的内容和美观的设计。')

            .fontSize(14)

            .fontColor('#666666')

            .lineHeight(20)

 

          Row({ space: 10 }) {

            Button('👍 点赞')

              .height(32)

              .fontSize(12)

              .backgroundColor('#3498DB')

              .borderRadius(16)

 

            Button('💬 评论')

              .height(32)

              .fontSize(12)

              .backgroundColor('#27AE60')

              .borderRadius(16)

 

            Button('🔗 分享')

              .height(32)

              .fontSize(12)

              .backgroundColor('#E67E22')

              .borderRadius(16)

          }

          .width('100%')

          .justifyContent(FlexAlign.Start)

        }

        .width('100%')

        .padding(20)

        .backgroundColor(Color.White)

        .borderRadius(15)

        .shadow({

          radius: 10,

          color: '#20000000',

          offsetX: 0,

          offsetY: 5

        })

      }

 

      // 图文混排列表项

      ListItem() {

        Row({ space: 15 }) {

          Column({ space: 8 }) {

            Text('🖼️')

              .fontSize(40)

            Text('图片')

              .fontSize(12)

              .fontColor('#666666')

          }

          .width(80)

          .alignItems(HorizontalAlign.Center)

 

          Column({ space: 8 }) {

            Text('图文混排列表项')

              .fontSize(16)

              .fontWeight(FontWeight.Medium)

              .fontColor('#333333')

 

            Text('展示图片和文字的完美结合,适用于商品展示、文章列表等场景。')

              .fontSize(14)

              .fontColor('#666666')

              .maxLines(3)

              .textOverflow({ overflow: TextOverflow.Ellipsis })

 

            Row({ space: 15 }) {

              Text('⭐ 4.8')

                .fontSize(12)

                .fontColor('#FF9800')

 

              Text('💰 ¥99')

                .fontSize(14)

                .fontWeight(FontWeight.Bold)

                .fontColor('#E74C3C')

            }

          }

          .layoutWeight(1)

          .alignItems(HorizontalAlign.Start)

        }

        .width('100%')

        .padding(15)

        .backgroundColor(Color.White)

        .borderRadius(12)

        .shadow({

          radius: 5,

          color: '#10000000',

          offsetX: 0,

          offsetY: 2

        })

      }

 

      // 进度条列表项

      ListItem() {

        Column({ space: 12 }) {

          Row() {

            Text('📊 项目进度')

              .fontSize(16)

              .fontWeight(FontWeight.Medium)

              .fontColor('#333333')

              .layoutWeight(1)

 

            Text('75%')

              .fontSize(14)

              .fontWeight(FontWeight.Bold)

              .fontColor('#27AE60')

          }

          .width('100%')

 

          Progress({ value: 75, total: 100, type: ProgressType.Linear })

            .width('100%')

            .height(8)

            .color('#27AE60')

            .backgroundColor('#E8F5E8')

 

          Text('项目开发进展顺利,预计下周完成主要功能开发。')

            .fontSize(14)

            .fontColor('#666666')

        }

        .width('100%')

        .padding(20)

        .backgroundColor(Color.White)

        .borderRadius(12)

        .shadow({

          radius: 5,

          color: '#10000000',

          offsetX: 0,

          offsetY: 2

        })

      }

 

      // 统计数据列表项

      ListItem() {

        Column({ space: 15 }) {

          Text('📈 数据统计')

            .fontSize(16)

            .fontWeight(FontWeight.Medium)

            .fontColor('#333333')

 

          Row({ space: 20 }) {

            Column({ space: 5 }) {

              Text('1,234')

                .fontSize(20)

                .fontWeight(FontWeight.Bold)

                .fontColor('#3498DB')

 

              Text('访问量')

                .fontSize(12)

                .fontColor('#666666')

            }

            .layoutWeight(1)

 

            Column({ space: 5 }) {

              Text('567')

                .fontSize(20)

                .fontWeight(FontWeight.Bold)

                .fontColor('#27AE60')

 

              Text('用户数')

                .fontSize(12)

                .fontColor('#666666')

            }

            .layoutWeight(1)

 

            Column({ space: 5 }) {

              Text('89')

                .fontSize(20)

                .fontWeight(FontWeight.Bold)

                .fontColor('#E67E22')

 

              Text('订单数')

                .fontSize(12)

                .fontColor('#666666')

            }

            .layoutWeight(1)

          }

          .width('100%')

        }

        .width('100%')

        .padding(20)

        .backgroundColor(Color.White)

        .borderRadius(12)

        .shadow({

          radius: 5,

          color: '#10000000',

          offsetX: 0,

          offsetY: 2

        })

      }

    }

    .layoutWeight(1)

    .padding({ left: 20, right: 20 })

  }

 

  // 构建滑动操作

  @Builder

  buildSwipeActions(id: number, type: string) {

    Row({ space: 10 }) {

      Button('编辑')

        .width(60)

        .height(40)

        .fontSize(12)

        .backgroundColor('#3498DB')

        .borderRadius(8)

        .onClick(() => {

          console.log(`编辑${type}: ${id}`)

        })

 

      Button('删除')

        .width(60)

        .height(40)

        .fontSize(12)

        .backgroundColor('#E74C3C')

        .borderRadius(8)

        .onClick(() => {

          this.deleteItem(id, type)

        })

    }

    .padding({ right: 10 })

  }

 

  // 获取过滤后的联系人

  getFilteredContacts(): ContactItem[] {

    if (!this.searchText) {

      return this.contactList

    }

    return this.contactList.filter(contact =>

      contact.name.includes(this.searchText) ||

      contact.phone.includes(this.searchText)

    )

  }

 

  // 重置选择状态

  resetSelection() {

    this.isMultiSelect = false

    this.selectedItems.clear()

    this.searchText = ''

  }

 

  // 删除选中的联系人

  deleteSelectedContacts() {

    this.contactList = this.contactList.filter(contact =>

      !this.selectedItems.has(contact.id)

    )

    this.selectedItems.clear()

    this.isMultiSelect = false

  }

 

  // 删除项目

  deleteItem(id: number, type: string) {

    if (type === 'contact') {

      this.contactList = this.contactList.filter(item => item.id !== id)

    } else if (type === 'news') {

      this.newsList = this.newsList.filter(item => item.id !== id)

    } else if (type === 'todo') {

      this.todoList = this.todoList.filter(item => item.id !== id)

    }

  }

 

  // 添加待办事项

  addTodoItem() {

    const newId = Math.max(...this.todoList.map(item => item.id)) + 1

    const newTodo: TodoItem = {

      id: newId,

      title: `新待办事项 ${newId}`,

      completed: false,

      priority: 'medium'

    }

    this.todoList.unshift(newTodo)

  }

 

  // 更新待办状态

  updateTodoStatus(id: number, completed: boolean) {

    const index = this.todoList.findIndex(item => item.id === id)

    if (index !== -1) {

      this.todoList[index].completed = completed

    }

  }

 

  // 获取优先级文本

  getPriorityText(priority: string): string {

    switch (priority) {

      case 'high': return '高优先级'

      case 'medium': return '中优先级'

      case 'low': return '低优先级'

      default: return '普通'

    }

  }

 

  // 获取优先级颜色

  getPriorityColor(priority: string): string {

    switch (priority) {

      case 'high': return '#E74C3C'

      case 'medium': return '#F39C12'

      case 'low': return '#27AE60'

      default: return '#95A5A6'

    }

  }

 

  // 获取优先级背景色

  getPriorityBgColor(priority: string): string {

    switch (priority) {

      case 'high': return '#FADBD8'

      case 'medium': return '#FCF3CF'

      case 'low': return '#D5DBDB'

      default: return '#F8F9FA'

    }

  }

 

  // 获取优先级图标

  getPriorityIcon(priority: string): string {

    switch (priority) {

      case 'high': return '🔴'

      case 'medium': return '🟡'

      case 'low': return '🟢'

      default: return '⚪'

    }

  }

}

```

 

### ⚙️ 配置文件

```json

// module.json5 配置

{

  "module": {

    "name": "entry",

    "type": "entry",

    "description": "$string:module_desc",

    "mainElement": "EntryAbility",

    "deviceTypes": [

      "phone",

      "tablet"

    ],

    "deliveryWithInstall": true,

    "installationFree": false,

    "pages": "$profile:main_pages",

    "abilities": [

      {

        "name": "EntryAbility",

        "srcEntry": "./ets/entryability/EntryAbility.ts",

        "description": "$string:EntryAbility_desc",

        "icon": "$media:icon",

        "label": "$string:EntryAbility_label",

        "startWindowIcon": "$media:icon",

        "startWindowBackground": "$color:start_window_background"

      }

    ]

  }

}

```

 

---

 

## 🚀 运行效果

 

### 📱 界面展示

运行后的界面将展示:

- 📋 渐变色标题,展示List组件主题

- 🏷️ 四个标签页:联系人、新闻、待办、自定义

- 📞 **联系人列表**:带搜索、多选、滑动删除功能

- 📰 **新闻列表**:图文混排,分类标签展示

- ✅ **待办列表**:可勾选完成状态,优先级标识

- 🎨 **自定义列表**:卡片式、进度条、统计数据等多种样式

 

### ✅ 功能验证

1. **基础功能**:切换标签页,查看不同类型列表

2. **搜索功能**:在联系人页面输入关键词搜索

3. **多选操作**:点击"选择"按钮,批量选择联系人

4. **滑动删除**:左滑列表项,点击删除按钮

5. **状态切换**:在待办列表中勾选完成状态

6. **添加功能**:点击"添加待办"按钮新增项目

 

---

 

## 💡 开发小贴士

 

### 🎯 最佳实践

- 💫 **性能优化**:大数据列表使用LazyForEach,避免一次性渲染

- 🎨 **视觉设计**:合理使用间距、圆角、阴影提升视觉效果

- ⚡ **交互反馈**:提供清晰的点击、滑动、选择状态反馈

- 🔧 **数据管理**:使用@State管理列表数据,确保界面及时更新

 

### 🚨 常见问题

1. **列表不更新**:确保使用@State装饰器管理数据状态

2. **滑动卡顿**:检查列表项是否过于复杂,考虑使用LazyForEach

3. **滑动操作失效**:确保swipeAction正确配置,注意手势冲突

 

### 📚 扩展学习

- **虚拟滚动**:学习LazyForEach的高级用法和性能优化

- **自定义动画**:为列表项添加进入、退出动画效果

- **无限滚动**:实现下拉刷新和上拉加载更多功能

 

---

 

## 🎉 总结与展望

 

通过这个Demo,我们学习了:

- ✨ List组件的基础使用和高级特性

- 🎯 不同类型列表的设计和实现方法

- 💡 列表交互功能的开发技巧

- 🎨 创建美观列表界面的设计原则

 

List组件作为移动应用中最常用的容器组件之一,掌握其各种用法对于创建优秀的用户体验至关重要。从简单的文本列表到复杂的交互列表,每一个细节都体现着应用的专业性。

 

希望这个示例能够帮助到正在学习HarmonyOS开发的你!下一期我们将探索更多有趣的容器组件,敬请期待!如果你有任何问题或建议,欢迎在评论区留言交流。

 

---

 

## 🔗 相关资源

 

- 📚 [HarmonyOS官方文档](https://developer.harmonyos.com/)

- 🛠️ [DevEco Studio下载](https://developer.harmonyos.com/cn/develop/deveco-studio)

- 💬 [坚果派技术社区](https://www.nutpi.net/)

- 🎨 [HarmonyOS设计规范](https://developer.harmonyos.com/cn/design/)

 

---

 

<div align="center">

 

**🌟 如果这篇文章对你有帮助,请点赞支持!🌟**

 

*让我们一起在HarmonyOS的世界里创造更多可能!*

 

---

 

*© 2024 坚果派·红目香薰 | 用心分享,用技术创造价值*

 

</div>

 

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐