一、组件介绍
TextPicker组件是HarmonyOS NEXT中用于文本选择的交互组件,它提供了一个滚动选择器界面,允许用户从预设的文本选项中进行选择。
二、基本概念
1. 组件定义
TextPicker是一个文本选择器组件,通过滚动方式展示一组文本选项,用户可以通过滚动或点击选择所需的文本项。
三、组件特性
1. 基本属性
- defaultPickerItemHeight:选项默认高度
- selected:当前选中项的索引
- value:文本选项数组
- defaultSelect:默认选中项
2. 事件处理
- onChange:选择变化事件
- onAccept:确认选择事件
- onCancel:取消选择事件
3. 样式定制
- textStyle:文本样式
- selectedTextStyle:选中项文本样式
- backgroundColor:背景颜色
- dividerColor:分隔线颜色
四、使用指南
1. 基本用法
@Entry
@Component
struct TextPickerExample {
private fruits: string[] = ['苹果', '香蕉', '橙子', '葡萄', '西瓜']
@State selectedIndex: number = 0
build() {
Column() {
TextPicker({
value: this.fruits,
selected: this.selectedIndex
})
.onChange((index: number) => {
this.selectedIndex = index
})
.width('80%')
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
2. 自定义样式
@Entry
@Component
struct CustomStyleExample {
private options: string[] = ['选项1', '选项2', '选项3', '选项4', '选项5']
@State selectedIndex: number = 0
build() {
Column() {
TextPicker({
value: this.options,
selected: this.selectedIndex
})
.onChange((index: number) => {
this.selectedIndex = index
})
.width('80%')
.height(200)
.textStyle({
fontSize: 16,
color: '#666666'
})
.selectedTextStyle({
fontSize: 20,
color: '#2196F3',
fontWeight: FontWeight.Bold
})
.backgroundColor('#F5F5F5')
.dividerColor('#CCCCCC')
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
3. 事件处理
@Entry
@Component
struct EventHandlingExample {
private categories: string[] = ['分类1', '分类2', '分类3', '分类4', '分类5']
@State selectedIndex: number = 0
build() {
Column() {
TextPicker({
value: this.categories,
selected: this.selectedIndex
})
.onChange((index: number) => {
this.selectedIndex = index
console.info('当前选中项:', this.categories[index])
})
.onAccept(() => {
console.info('确认选择:', this.categories[this.selectedIndex])
})
.onCancel(() => {
console.info('取消选择')
})
.width('80%')
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
4. 动态数据
@Entry
@Component
struct DynamicDataExample {
@State options: string[] = []
@State selectedIndex: number = 0
aboutToAppear() {
// 模拟异步加载数据
setTimeout(() => {
this.options = ['数据1', '数据2', '数据3', '数据4', '数据5']
}, 1000)
}
build() {
Column() {
if (this.options.length > 0) {
TextPicker({
value: this.options,
selected: this.selectedIndex
})
.onChange((index: number) => {
this.selectedIndex = index
})
.width('80%')
} else {
LoadingProgress()
.width(50)
.height(50)
}
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
五、总结
本案例详细介绍了HarmonyOS NEXT中TextPicker组件的使用方法,包括基本用法、样式定制、事件处理和动态数据加载。通过实例展示了如何实现文本选择器的功能,帮助开发者快速掌握TextPicker组件的特性和应用场景。