
回复
在做联系人、城市、商品分类等长列表页面时,很多同学都想加一个侧边字母快速索引,像原生通讯录那样一滑到“A”,列表直接定位。HarmonyOS ArkTS 里,AlphabetIndexer 就是专门解决这个需求的神器。本指南带你从0上手,掌握各种常用用法和进阶技巧。
AlphabetIndexer 是侧边索引栏组件,通常配合 List、Grid 等容器使用。
典型场景有:
用它,可以让你的列表“秒到目标”,提升大长列表的可用性和高级感。
来看一个最简单的用法:
@Entry
@Component
struct SimpleAlphaIndexer {
private indexList: string[] = [
'#', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z'
]
@State selectedIndex: number = 0
build() {
Row() {
// 假装这里是列表
Column() {
Text('模拟内容区').fontSize(22).margin(20)
}.width('75%')
// 侧边索引
AlphabetIndexer({ arrayValue: this.indexList, selected: this.selectedIndex })
.height('60%')
.width('auto')
.selectedColor(0xFF007DFF) // 选中项颜色
.color(0x99182431) // 未选中项颜色
.itemSize(26) // 每个字母的高度
.selectedBackgroundColor(0x1A007DFF)
.usingPopup(true) // 开启提示弹窗
.popupBackground(0xFAFAFA)
.onSelect((index: number) => {
this.selectedIndex = index
console.info(`当前选中:${this.indexList[index]}`)
// 这里通常做滚动定位等逻辑
})
}.width('100%').height(480)
}
}
重点参数解释:
通常用法是AlphabetIndexer和List放在同一个页面,索引点击后跳转到指定位置。你可以这样:
@Entry
@Component
struct AlphaWithList {
private alphaArr: string[] = ['A', 'B', 'C', 'D', 'E']
private listMap: Record<string, string[]> = {
'A': ['阿狸', '安琪'],
'B': ['布鲁', '白雪'],
'C': ['曹操', '陈皮'],
'D': ['大勇', '丁一'],
'E': ['二狗', '尔东']
}
@State selectedIndex: number = 0
@State listScrollIndex: number = 0
build() {
Row({ space: 10 }) {
List({ initialIndex: this.listScrollIndex }) {
ForEach(this.alphaArr, (alpha: string) => {
ListItem() {
Column({ space: 8 }) {
Text(alpha).fontWeight(FontWeight.Bold).fontSize(18).fontColor('#007dff').margin({ left: 8 })
ForEach(this.listMap[alpha], (item: string) => {
Text(item).fontSize(16).fontColor('#222').margin({ left: 22 })
}, (item: string) => item) // 明确指定 item 类型为 string
}
}
}, (alpha: string) => alpha)
}.width('70%').height(320)
AlphabetIndexer({ arrayValue: this.alphaArr, selected: this.selectedIndex })
.usingPopup(true)
.popupBackground(0xEEEEEE)
.selectedBackgroundColor(0xAA007dFF)
.selectedColor(0xFFFFFF)
.itemSize(28)
.onSelect((index: number) => {
this.selectedIndex = index
this.listScrollIndex = index // 切换索引,滚动到对应分组
})
}.width('100%').height(340)
}
}
有些场景,比如通讯录,“L”下面有很多名字,滑动到 “L” 时可以弹窗显示更细的二级列表。你可以通过 onRequestPopupData 实现:
AlphabetIndexer({
arrayValue: ['A', 'B', 'L'],
selected: this.selectedIndex
})
.usingPopup(true)
.onRequestPopupData((index: number) => {
if (index === 2) {
// 比如“L”下面有很多人名
return ['刘一', '李二', '陆三', '林四', '卢五']
}
return []
})
.onPopupSelect((popupIdx: number) => {
// 选中了二级弹窗的第几个
console.info(`弹窗选中:${popupIdx}`)
})
AlphabetIndexer 提供丰富的属性让你做个性化美化,常用的有:
还可以折叠显示过多字母 .autoCollapse(true)、.popupBackgroundBlurStyle(BlurStyle.COMPONENT_REGULAR) 增加模糊等效果。
AlphabetIndexer 让你的列表拥有原生App的分组索引体验,适合做联系人、商品分区、城市列表等场景。
支持丰富的样式和弹窗配置,兼容双向数据绑定、国际化和折叠优化。
联动 List、Column 等容器做高效跳转,体验大幅提升。