
回复
哈喽大家好呀,最近在研究鸿蒙开发,发现里面有个挺有意思的组件,叫做TextPickerDialog,也就是我们常见的那种滑动选择器弹窗。你肯定经常在各种App里见到过,比如选个城市、选个水果之类的,都喜欢用这种滑动的方式,显得特别丝滑舒服。
今天呢,我就带着大家,从零开始了解怎么用鸿蒙自带的这个TextPickerDialog,手把手带你实现出来,还教你怎么给它加点自定义的小样式。
废话不多说,咱们直接上手来个最基础的实现,先让它跑起来再说!
// TextPickerDialogExample.ets
@Entry
@Component
struct TextPickerDialogExample {
private currentIndex: number = 0
private animals: string[] = ['小猫🐱', '小狗🐶', '小兔子🐰', '小狐狸🦊', '小熊🐻']
@State selectedAnimal: string = '';
build() {
Column() {
Button("选个萌宠🐾: " + this.selectedAnimal)
.margin(30)
.backgroundColor('#FFBB86FC')
.fontSize('18fp')
.fontWeight(FontWeight.Bold)
.borderRadius(12)
.onClick(() => {
TextPickerDialog.show({
range: this.animals,
selected: this.currentIndex,
onAccept: (result) => {
this.selectedAnimal = result.value as string;
console.log("你选了:" + this.selectedAnimal);
},
onCancel: () => console.log("取消选择啦😢"),
onChange: (result) => console.log("当前滑到:" + result.value),
});
});
}.width('100%').height('100%').justifyContent(FlexAlign.Center);
}
}
运行之后,点一下按钮,就能看到萌宠的选择列表啦~是不是特别简单呢?
刚刚的实现是基础版,能用,但不够炫酷。咱们程序员嘛,还是得有点审美追求的,对吧?下面咱们来点个性化定制!
TextPickerDialog.show({
range: this.animals,
selected: this.currentIndex,
canLoop: true, // 允许无限循环,选起来更舒服
disappearTextStyle: {color: '#CCCCCC', font: {size: '14fp', weight: FontWeight.Lighter}},
textStyle: {color: '#333333', font: {size: '18fp', weight: FontWeight.Regular}},
selectedTextStyle: {color: '#6200EE', font: {size: '24fp', weight: FontWeight.Bold}},
acceptButtonStyle: {
fontColor: '#FFFFFF',
backgroundColor: '#6200EE',
borderRadius: 15,
fontSize: '20fp',
fontWeight: FontWeight.Bold,
primary: true
},
cancelButtonStyle: {
fontColor: '#6200EE',
backgroundColor: '#EDE7F6',
borderRadius: 15,
fontSize: '18fp'
},
backgroundBlurStyle: BlurStyle.NONE,
backgroundColor: '#FFFFFF',
onAccept: (result) => {
this.selectedAnimal = result.value as string;
console.log("确认选择:" + this.selectedAnimal);
},
onCancel: () => console.log("取消了哦🤔")
});
这里我做了几个小改动:
选项字体颜色做了明显区分,突出选中项。
按钮变成了圆润的样子,颜色也更现代。
背景设置为纯白色,让弹窗更加清爽。
如果你有折叠屏设备,鸿蒙还提供了特别贴心的悬停模式优化。咱们来看下怎么实现吧:
TextPickerDialog.show({
range: this.animals,
selected: this.currentIndex,
enableHoverMode: true,
hoverModeArea: HoverModeAreaType.TOP_SCREEN,
selectedTextStyle: {color: '#FF018786', font: {size: '26fp', weight: FontWeight.Regular}},
onAccept: (result) => {
this.selectedAnimal = result.value as string;
console.log("悬停模式选中:" + this.selectedAnimal);
}
});
开启悬停模式后,当设备处于半折叠状态,选择器会自动适应屏幕布局,使用体验真的是太棒了!
如果你想监听弹窗的完整生命周期,这里有几个特别实用的回调方法,比如:
onDidAppear:弹窗弹出完成后触发。
onWillDisappear:弹窗即将消失前触发。
举个例子:
TextPickerDialog.show({
range: this.animals,
selected: this.currentIndex,
onDidAppear: () => console.log("弹窗已经出现啦🚀"),
onWillDisappear: () => console.log("弹窗马上要消失咯👋")
});
总的来说,TextPickerDialog组件在鸿蒙开发里真的非常好用,而且自由度也很高。不论你是新手,还是想深入学习的朋友,都可以拿这个组件来练练手,从最简单的基础用法到个性化的定制,都能轻松实现。
好了,今天的分享就到这儿了,如果大家有什么问题或者更好的创意,欢迎留言互动哦!咱们一起玩转鸿蒙开发吧,加油💪!