温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

OpenHarmony ListView如何定制

发布时间:2026-11-01 02:14:52 来源:亿速云 阅读:97 作者:小樊 栏目:软件技术

在 OpenHarmony(ArkUI) 里,早期叫 ListView,在 ArkTS / eTS 新架构中通常对应的是 List + ListItem / ListItemGroup 组件。下面从基础用法 → 常见定制方式给你系统讲一下。


一、基础 ListView(List)用法

@Entry
@Component
struct ListViewExample {
  private data: string[] = ['A', 'B', 'C', 'D']

  build() {
    List() {
      ForEach(this.data, (item: string) => {
        ListItem() {
          Text(item)
            .fontSize(20)
            .padding(10)
        }
      })
    }
    .width('100%')
    .height('100%')
  }
}

二、常见定制方式

1️⃣ 自定义 Item 布局(最常用)

ListItem() {
  Row() {
    Image($r('app.media.icon'))
      .width(40)
      .height(40)
    Text(item)
      .margin({ left: 10 })
  }
  .padding(10)
}

✅ 可任意组合:

  • Text / Image / Button
  • Row / Column / Stack

2️⃣ 设置滚动方向(横向 / 纵向)

List() {
  // items
}
.listDirection(Axis.Horizontal) // 横向

默认是 Axis.Vertical


3️⃣ 分割线(divider)

List() {
  // items
}
.divider({
  strokeWidth: 1,
  color: '#eee',
  startMargin: 10,
  endMargin: 10
})

4️⃣ 列表分组(ListItemGroup)

List() {
  ListItemGroup({ header: this.groupHeader('Group 1') }) {
    ListItem() { Text('Item 1') }
    ListItem() { Text('Item 2') }
  }
}

@Builder
groupHeader(title: string) {
  Text(title)
    .fontSize(18)
    .fontWeight(FontWeight.Bold)
    .padding(10)
}

5️⃣ 点击事件

ListItem() {
  Text(item)
}
.onClick(() => {
  console.log('clicked:', item)
})

6️⃣ 下拉刷新 / 上拉加载(自定义)

OpenHarmony 没有内置 Refresh 组件(旧版本),可这样实现:

下拉刷新(示例思路)

List() {
  // header
  ListItem() {
    Text('下拉刷新...')
  }
}
.onScrollIndex((start, end) => {
  if (start === 0) {
    // 触发刷新
  }
})

✅ 新版本可用 Refresh 组件(API 10+)

Refresh({ refreshing: this.isRefreshing }) {
  List() {
    // items
  }
}
.onRefreshing(() => {
  // 加载数据
})

7️⃣ 性能优化(关键)

✅ 使用 cachedCount

List() {
  // items
}
.cachedCount(5)

✅ 大数据用 LazyForEach

List() {
  LazyForEach(this.dataSource, (item) => {
    ListItem() {
      Text(item)
    }
  })
}

三、旧版 ListView(JS / eTS 兼容)

旧版:

<list>
  <list-item for="{{list}}">
    <text>{{$item}}</text>
  </list-item>
</list>

⚠️ 新项目不推荐,建议用 ArkTS


四、总结

需求 实现方式
自定义 item ListItem + 布局
分组 ListItemGroup
分割线 divider
横向列表 listDirection
刷新 Refresh
性能 LazyForEach

如果你有 具体场景(比如聊天列表、设置页、瀑布流、RecyclerView 迁移),我可以给你完整示例代码。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手