HarmonyOS鸿蒙Next中如何使用AlertDialog和@CustomDialog实现弹窗功能?

HarmonyOS鸿蒙Next中如何使用AlertDialog和@CustomDialog实现弹窗功能? 我需要在应用中显示确认弹窗和自定义弹窗,想了解:

  1. AlertDialog.show() 如何显示系统确认弹窗?
  2. @CustomDialog 装饰器如何创建自定义弹窗组件?
  3. CustomDialogController 如何控制弹窗的打开和关闭?
  4. 如何向自定义弹窗传递参数?
  5. 如何从弹窗中获取用户的操作结果(确认/取消)?

希望能获取弹窗功能的完整代码示例。

3 回复

实现思路:

  1. 使用 AlertDialog.show 显示系统确认弹窗:
AlertDialog.show({
  title: '提示',
  message: '确定要删除吗?',
  primaryButton: {
    value: '取消',
    action: () => console.info('取消')
  },
  secondaryButton: {
    value: '确定',
    action: () => this.deleteItem()
  }
});
  1. 使用 @CustomDialog 创建自定义弹窗组件:
[@CustomDialog](/user/CustomDialog)
struct EditDialog {
  controller: CustomDialogController;
  onConfirm: (value: string) => void = () => {};
  @State inputValue: string = '';

  build() {
    Column({ space: 16 }) {
      Text('编辑').fontSize(18).fontWeight(FontWeight.Bold)
      TextInput({ text: this.inputValue })
        .onChange((value: string) => this.inputValue = value)
      Row({ space: 16 }) {
        Button('取消').onClick(() => this.controller.close())
        Button('确定').onClick(() => {
          this.onConfirm(this.inputValue);
          this.controller.close();
        })
      }
    }
    .padding(24)
  }
}
  1. 使用 CustomDialogController 控制弹窗:
dialogController: CustomDialogController = new CustomDialogController({
  builder: EditDialog({
    onConfirm: (value: string) => {
      console.info(`确认: ${value}`);
    }
  }),
  autoCancel: true
});

// 打开弹窗
this.dialogController.open();
  1. 完整示例代码:
@Entry
@Component
struct DialogExample {
  @State content: string = '初始内容';

  dialogController: CustomDialogController = new CustomDialogController({
    builder: EditDialog({
      initialValue: this.content,
      onConfirm: (value: string) => {
        this.content = value;
      }
    }),
    autoCancel: true,
    alignment: DialogAlignment.Center,
    customStyle: true
  });

  showAlertDialog() {
    AlertDialog.show({
      title: '提示',
      message: '确定要删除这条记录吗?',
      autoCancel: true,
      primaryButton: {
        value: '取消',
        action: () => console.info('取消')
      },
      secondaryButton: {
        value: '确定',
        fontColor: Color.Red,
        action: () => {
          console.info('确定删除');
          this.content = '';
        }
      }
    });
  }

  build() {
    Column({ space: 16 }) {
      Text(`当前内容: ${this.content}`)
        .fontSize(16)

      Button('显示系统弹窗')
        .onClick(() => this.showAlertDialog())

      Button('显示自定义弹窗')
        .onClick(() => this.dialogController.open())
    }
    .width('100%')
    .padding(20)
  }
}

[@CustomDialog](/user/CustomDialog)
struct EditDialog {
  controller: CustomDialogController;
  initialValue: string = '';
  onConfirm: (value: string) => void = () => {};
  @State inputValue: string = '';

  aboutToAppear() {
    this.inputValue = this.initialValue;
  }

  build() {
    Column({ space: 16 }) {
      Text('编辑内容')
        .fontSize(18)
        .fontWeight(FontWeight.Bold)

      TextInput({ text: this.inputValue, placeholder: '请输入内容' })
        .onChange((value: string) => this.inputValue = value)

      Row({ space: 16 }) {
        Button('取消')
          .backgroundColor('#F0F0F0')
          .fontColor('#333')
          .onClick(() => this.controller.close())

        Button('确定')
          .onClick(() => {
            this.onConfirm(this.inputValue);
            this.controller.close();
          })
      }
    }
    .padding(24)
    .backgroundColor(Color.White)
    .borderRadius(16)
    .width('80%')
  }
}

更多关于HarmonyOS鸿蒙Next中如何使用AlertDialog和@CustomDialog实现弹窗功能?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,AlertDialog和@CustomDialog用于实现弹窗功能。

AlertDialog是系统提供的标准弹窗组件,通过AlertDialog.show()方法创建并显示,可设置标题、消息和按钮。

@CustomDialog是装饰器,用于自定义弹窗。使用步骤:

  1. @CustomDialog装饰自定义弹窗组件。
  2. 在组件内使用Column、Text等布局内容。
  3. 通过controller.open()打开弹窗。

两者区别:AlertDialog用于简单提示,@CustomDialog用于复杂自定义UI。

在HarmonyOS Next中,AlertDialog和@CustomDialog是两种主要的弹窗实现方式。

1. AlertDialog.show() 显示系统确认弹窗 AlertDialog.show()提供标准系统弹窗,支持标题、消息和按钮配置。

import { AlertDialog } from '@ohos.arkui.advanced.AlertDialog';

// 显示确认弹窗
AlertDialog.show({
  title: '确认操作',
  message: '确定要删除此项吗?',
  primaryButton: {
    value: '取消',
    action: () => {
      console.log('用户点击了取消');
    }
  },
  secondaryButton: {
    value: '确认',
    action: () => {
      console.log('用户点击了确认');
    }
  }
});

2. @CustomDialog 创建自定义弹窗组件 使用@CustomDialog装饰器定义可复用的自定义弹窗组件。

import { CustomDialog } from '@ohos.arkui.advanced.CustomDialog';

[@CustomDialog](/user/CustomDialog)
struct MyCustomDialog {
  // 弹窗内容
  build() {
    Column() {
      Text('自定义弹窗内容')
        .fontSize(20)
        .margin(20)
    }
  }
}

3. CustomDialogController 控制弹窗 CustomDialogController管理自定义弹窗的生命周期。

@Entry
@Component
struct Index {
  private dialogController: CustomDialogController = new CustomDialogController({
    builder: MyCustomDialog(),
    cancel: () => {
      console.log('弹窗关闭');
    }
  });

  build() {
    Column() {
      Button('打开弹窗')
        .onClick(() => {
          this.dialogController.open(); // 打开弹窗
        })
    }
  }
}

4. 向自定义弹窗传递参数 通过构造函数或@Prop装饰器传递参数。

[@CustomDialog](/user/CustomDialog)
struct ParamDialog {
  [@Prop](/user/Prop) message: string = '';

  build() {
    Column() {
      Text(this.message)
        .fontSize(18)
    }
  }
}

// 使用
new CustomDialogController({
  builder: ParamDialog({ message: '来自父组件的参数' })
});

5. 获取用户操作结果 通过回调函数或@Link装饰器返回结果。

[@CustomDialog](/user/CustomDialog)
struct ResultDialog {
  [@Link](/user/Link) isConfirmed: boolean;

  build() {
    Column() {
      Button('确认')
        .onClick(() => {
          this.isConfirmed = true;
          // 关闭逻辑
        })
      Button('取消')
        .onClick(() => {
          this.isConfirmed = false;
          // 关闭逻辑
        })
    }
  }
}

// 父组件中
@State confirmResult: boolean = false;
private dialogController: CustomDialogController = new CustomDialogController({
  builder: ResultDialog({ isConfirmed: $confirmResult }),
  cancel: () => {
    console.log(`用户选择结果: ${this.confirmResult}`);
  }
});

完整示例:带参数和结果的自定义弹窗

// 自定义弹窗组件
[@CustomDialog](/user/CustomDialog)
struct CompleteDialog {
  [@Prop](/user/Prop) title: string;
  [@Link](/user/Link) result: boolean;

  build() {
    Column() {
      Text(this.title)
        .fontSize(20)
        .margin(10)

      Row() {
        Button('取消')
          .onClick(() => {
            this.result = false;
            // 实际使用中通过controller关闭
          })
        Button('确认')
          .onClick(() => {
            this.result = true;
          })
      }
    }
  }
}

// 使用页面
@Entry
@Component
struct MainPage {
  @State dialogResult: boolean = false;
  private controller: CustomDialogController = new CustomDialogController({
    builder: CompleteDialog({
      title: '操作确认',
      result: $dialogResult
    }),
    cancel: () => {
      console.log(`操作结果: ${this.dialogResult}`);
    }
  });

  build() {
    Column() {
      Button('显示弹窗')
        .onClick(() => {
          this.controller.open();
        })
    }
  }
}

AlertDialog适用于简单标准弹窗,@CustomDialog适合需要自定义UI和复杂交互的场景。两者都支持异步操作和结果回调。

回到顶部