总体思路如下:通过实现AlertDialog的AlertDialogButtonOptions接口,定义一个CustomAlertDialogButtonOptions类,并通过自定义的函数将普通数组转化为AlertDialog的AlertDialogParamWithOptions需要的类型即可实现需求。
class CustomAlertDialogButtonOptions implements AlertDialogButtonOptions {
value: string = '保存';
buttonIndex: number = -1;
action = () => {
console.info('Callback when button1 is clicked');
};
} setDialogButtonWithList(list: number[]): CustomAlertDialogButtonOptions[] {
let tempList: CustomAlertDialogButtonOptions[] = [];
for (let index = 0; index < list.length; index++) {
const element = list[index];
tempList.push({
value: element.toString(),
buttonIndex: index,
action: () => {
switch (index) {
// 根据index做对应的逻辑处理
case 0:
this.title = '选中了第一项';
break;
case 1:
this.title = '选中了第二项';
break;
case 2:
this.title = '选中了第三项';
break;
case 3:
this.title = '选中了第四项';
break;
}
console.info('Callback when button is clicked index =', index);
}
});
}
return tempList;
} 完整示例参考如下:
class CustomAlertDialogButtonOptions implements AlertDialogButtonOptions {
value: string = '保存';
buttonIndex: number = -1;
action = () => {
console.info('Callback when button1 is clicked');
};
}
@Entry
@Component
struct AlertDialogExample {
private list: number[] = [];
@State title: string = '';
// 模拟数据源
aboutToAppear(): void {
for (let index = 0; index < 4; index++) {
this.list.push(index);
}
}
setDialogButtonWithList(list: number[]): CustomAlertDialogButtonOptions[] {
let tempList: CustomAlertDialogButtonOptions[] = [];
for (let index = 0; index < list.length; index++) {
const element = list[index];
tempList.push({
value: element.toString(),
buttonIndex: index,
action: () => {
switch (index) {
// 根据index做对应的逻辑处理
case 0:
this.title = '选中了第一项';
break;
case 1:
this.title = '选中了第二项';
break;
case 2:
this.title = '选中了第三项';
break;
case 3:
this.title = '选中了第四项';
break;
}
console.info('Callback when button is clicked index =', index);
}
});
}
return tempList;
}
build() {
RelativeContainer() {
Button('多按钮弹窗')
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
this.getUIContext().showAlertDialog(
{
title: 'title',
subtitle: 'subtitle',
message: 'text',
autoCancel: true,
alignment: DialogAlignment.Bottom,
gridCount: 4,
buttonDirection: DialogButtonDirection.HORIZONTAL,
buttons: this.setDialogButtonWithList(this.list),
cancel: () => {
console.info('Closed callbacks');
},
onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
console.info(`reason= ${dismissDialogAction.reason}`);
console.info('AlertDialog onWillDismiss');
if (dismissDialogAction.reason === DismissReason.PRESS_BACK) {
dismissDialogAction.dismiss();
}
if (dismissDialogAction.reason === DismissReason.TOUCH_OUTSIDE) {
dismissDialogAction.dismiss();
}
}
}
);
}).backgroundColor(0x317aff);
Text(this.title)
.alignRules({
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.margin({ top: 50 });
}.width('100%').margin({ top: 5 });
}
}