arkts-common-components-custom-dialog.md 2.8 KB
Newer Older
H
HelloCrease 已提交
1
# 自定义弹窗(CustomDialog)
Z
zengyawen 已提交
2 3 4 5 6 7 8 9 10 11


自定义弹窗CustomDialog可用于广告、中奖、警告、软件更新等与用户交互响应操作。开发者可以通过CustomDialogController类显示自定义弹窗。具体用法请参考[自定义弹窗](../reference/arkui-ts/ts-methods-custom-dialog-box.md)


## 创建自定义弹窗

1. 使用\@CustomDialog装饰器装饰自定义弹窗。

2. \@CustomDialog装饰器用于装饰自定义弹框,此装饰器内进行自定义内容(也就是弹框内容)。
H
HelloCrease 已提交
12

Z
zengyawen 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
   ```ts
   @CustomDialog
   struct CustomDialogExample {
     controller: CustomDialogController
     build() {
       Column() {
         Text('我是内容')
         .fontSize(20)
         .margin({ top: 10, bottom: 10 })
       }
     }
   }
   ```

3. 创建构造器,与装饰器呼应相连。
H
HelloCrease 已提交
28

Z
zengyawen 已提交
29 30 31 32 33 34 35
   ```ts
   dialogController: CustomDialogController = new CustomDialogController({
       builder: CustomDialogExample({}),
   })
   ```

4. 点击与onClick事件绑定的组件使弹窗弹出
H
HelloCrease 已提交
36

Z
zengyawen 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
   ```ts
   Flex({justifyContent:FlexAlign.Center}){
     Button('click me')
       .onClick(() => {
         this.dialogController.open()
       })
   }.width('100%')
   ```

   ![zh-cn_image_0000001562700493](figures/zh-cn_image_0000001562700493.png)


## 弹窗的交互

弹窗可用于数据交互,完成用户一系列响应操作。


1.\@CustomDialog装饰器内添加按钮操作,同时添加数据函数的创建。
H
HelloCrease 已提交
55

Z
zengyawen 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
   ```ts
   @CustomDialog
   struct CustomDialogExample {
     controller: CustomDialogController
     cancel: () => void
     confirm: () => void
     build() {
       Column() {
         Text('我是内容').fontSize(20).margin({ top: 10, bottom: 10 })
         Flex({ justifyContent: FlexAlign.SpaceAround }) {
           Button('cancel')
             .onClick(() => {
               this.controller.close()
               this.cancel()
             }).backgroundColor(0xffffff).fontColor(Color.Black)
           Button('confirm')
             .onClick(() => {
               this.controller.close()
               this.confirm()
             }).backgroundColor(0xffffff).fontColor(Color.Red)
         }.margin({ bottom: 10 })
       }
     }
   }
   ```

2. 页面内需要在构造器内进行接收,同时创建相应的函数操作。
H
HelloCrease 已提交
83

Z
zengyawen 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
   ```ts
   dialogController: CustomDialogController = new CustomDialogController({
       builder: CustomDialogExample({
         cancel: this.onCancel,
         confirm: this.onAccept,
       }),
       alignment: DialogAlignment.Default,  // 可设置dialog的对齐方式,设定显示在底部或中间等,默认为底部显示
     })
     onCancel() {
       console.info('Callback when the first button is clicked')
     }
     onAccept() {
       console.info('Callback when the second button is clicked')
     }
   ```

   ![zh-cn_image_0000001511421320](figures/zh-cn_image_0000001511421320.png)