• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 自定义弹窗 (CustomDialog)
2<!--Kit: ArkUI-->
3<!--Subsystem: ArkUI-->
4<!--Owner: @houguobiao-->
5<!--Designer: @houguobiao-->
6<!--Tester: @lxl007-->
7<!--Adviser: @HelloCrease-->
8
9通过CustomDialogController类显示自定义弹窗。使用弹窗组件时,优先考虑自定义弹窗,便于弹窗样式与内容的自定义。
10
11> **说明:**
12>
13> 从API version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
14
15## CustomDialogController
16
17自定义弹窗的控制器。
18
19**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
20
21**系统能力:** SystemCapability.ArkUI.ArkUI.Full
22
23### 导入对象
24
25```ts
26dialogController : CustomDialogController | null = new CustomDialogController(CustomDialogControllerOptions)
27```
28> **说明:**
29>
30> - CustomDialogController仅在作为@CustomDialog和@Component struct成员变量,且在@Component struct内部定义时赋值才有效,具体用法可参考下方示例。
31>
32> - 若尝试在CustomDialog中传入多个其他的Controller,以实现在CustomDialog中打开另一个或另一些CustomDialog,那么此处需要将指向自己的controller放在所有controller的后面。详细用法可参考[示例1弹出嵌套弹窗](#示例1弹出嵌套弹窗)。
33
34### constructor
35
36constructor(value: CustomDialogControllerOptions)
37
38自定义弹窗的构造器。
39
40> **说明:**
41>
42> 自定义弹窗的所有参数,不支持动态刷新。
43>
44> 在CustomDialogController作为全局变量以实现全局自定义弹窗的场景下,若对controller重新赋值,则无法通过其关闭之前的弹窗。建议在重新赋值前先关闭弹窗。
45>
46> 在自定义弹窗内拉起另一个自定义弹窗时,不建议直接关闭拉起方。
47
48**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
49
50**系统能力:** SystemCapability.ArkUI.ArkUI.Full
51
52**参数:**
53
54| 参数名 | 类型                                                         | 必填 | 说明                   |
55| ------ | ------------------------------------------------------------ | ---- | ---------------------- |
56| value  | [CustomDialogControllerOptions](#customdialogcontrolleroptions对象说明) | 是   | 配置自定义弹窗的参数。 |
57
58### open
59
60open()
61
62显示自定义弹窗内容,允许多次使用,但如果弹框为SubWindow模式,则该弹框不允许再弹出SubWindow弹框。
63
64>  **说明:**
65>
66>  不支持在输入法类型窗口中使用子窗(showInSubwindow为true)的CustomDialog,详情见输入法框架的约束与限制说明[createPanel](../../apis-ime-kit/js-apis-inputmethodengine.md#createpanel10-1)。
67
68**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
69
70**系统能力:** SystemCapability.ArkUI.ArkUI.Full
71
72
73### close
74
75close()
76
77**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
78
79**系统能力:** SystemCapability.ArkUI.ArkUI.Full
80
81
82关闭显示的自定义弹窗,若已关闭,则不生效。
83
84### getState<sup>20+</sup>
85
86getState(): PromptActionCommonState
87
88获取自定义弹窗的状态。
89
90**原子化服务API:** 从API version 20开始,该接口支持在原子化服务中使用。
91
92**系统能力:** SystemCapability.ArkUI.ArkUI.Full
93
94**返回值:**
95
96| 类型 | 说明 |
97| -------- | -------- |
98| [PromptActionCommonState](#promptactioncommonstate20) | 返回对应的弹窗状态。 |
99
100## PromptActionCommonState<sup>20+</sup>
101
102type PromptActionCommonState = promptAction.CommonState
103
104自定义弹窗的状态。
105
106**原子化服务API:** 从API version 20开始,该接口支持在原子化服务中使用。
107
108**系统能力:** SystemCapability.ArkUI.ArkUI.Full
109
110| 类型 | 说明 |
111| -------- | -------- |
112| [promptAction.CommonState](../js-apis-promptAction.md#commonstate20枚举说明) | 返回对应的弹窗状态。 |
113
114## CustomDialogControllerOptions对象说明
115
116自定义弹窗的样式。
117
118**系统能力:** SystemCapability.ArkUI.ArkUI.Full
119
120| 名称                           | 类型                                     | 只读 | 可选 | 说明                                     |
121| ----------------------------- | ---------------------------------------- | ---- | ---------------------------------------- | ---------------------------------------- |
122| builder                       | [CustomDialog](../../../ui/arkts-common-components-custom-dialog.md) | 否   | 否   | 自定义弹窗内容构造器。<br/>**说明:** <br/>若builder构造器使用回调函数作为入参,请注意使用this绑定问题,如builder: custombuilder({ callback: ()=> {...}})。<br/>若在builder中监听数据变化可以使用@Link或@Consume,而其他方式如@Prop、@ObjectLink不适用此场景。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
123| cancel                        | ()&nbsp;=&gt;&nbsp;void                  | 否    | 是   | 返回、ESC键和点击遮障层弹窗退出时的回调。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
124| autoCancel                    | boolean                                  | 否    | 是   | 是否允许点击遮障层退出,true表示关闭弹窗。false表示不关闭弹窗。<br>默认值:true<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
125| alignment                     | [DialogAlignment](ts-methods-alert-dialog-box.md#dialogalignment枚举说明) | 否    | 是   | 弹窗在竖直方向上的对齐方式。<br>默认值:DialogAlignment.Default<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
126| offset                        | [Offset](ts-types.md#offset)             | 否    | 是   | 弹窗相对alignment所在位置的偏移量。<br/>默认值:{ dx: 0, dy: 0 }<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
127| customStyle                   | boolean                                  | 否    | 是   | 弹窗容器样式是否自定义。值为true表示弹窗容器样式不能自定义,值为false表示弹窗样式可以自定义。<br>设置false时(默认值):<br/>1.圆角为32vp。<br/>2.未设置弹窗宽度高度:弹窗容器的宽度根据栅格系统自适应。高度自适应自定义的内容节点。<br/>3.设置弹窗宽度高度:弹窗容器的宽度不超过默认样式下的最大宽度(自定义节点设置100%的宽度),弹窗容器的高度不超过默认样式下的最大高度(自定义节点设置100%的高度)。<br/>4.受安全区域的影响,弹窗显示区域将排除安全区域。<br/>设置为true:<br/>1.圆角为0,弹窗背景色为透明色。<br/>2.不支持设置弹窗宽度、高度、边框宽度、边框样式、边框颜色以及阴影宽度。<br/>3.弹窗显示区域为屏幕。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。|
128| gridCount<sup>8+</sup>        | number                                   | 否    | 是   | 弹窗宽度占[栅格宽度](../../../ui/arkts-layout-development-grid-layout.md)的个数。<br>默认为按照窗口大小自适应,异常值按默认值处理,最大栅格数为系统最大栅格数。<br/>取值范围:大于等于0的整数。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
129| maskColor<sup>10+</sup>       | [ResourceColor](ts-types.md#resourcecolor) | 否    | 是   | 自定义蒙层颜色。<br>默认值:0x33000000<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。              |
130| maskRect<sup>10+</sup>        | [Rectangle](ts-methods-alert-dialog-box.md#rectangle8类型说明) | 否     | 是    | 弹窗遮蔽层区域,在遮蔽层区域内的事件不透传,在遮蔽层区域外的事件透传。<br/>默认值:{ x: 0, y: 0, width: '100%', height: '100%' } <br/>**说明:**<br/>showInSubWindow为true时,maskRect不生效。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。|
131| openAnimation<sup>10+</sup>   | [AnimateParam](ts-explicit-animation.md#animateparam对象说明) | 否    | 是   | 自定义设置弹窗弹出的动画效果相关参数。<br>**说明**:<br>tempo默认值为1,当设置小于等于0的值时按默认值处理。<br/>iterations默认值为1,默认播放一次,设置为其他数值时按默认值处理。<br>playMode控制动画播放模式,默认值为PlayMode.Normal,设置为其他数值时按照默认值处理。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
132| closeAnimation<sup>10+</sup>  | [AnimateParam](ts-explicit-animation.md#animateparam对象说明) | 否    | 是   | 自定义设置弹窗关闭的动画效果相关参数。<br>**说明**:<br>tempo默认值为1,当设置小于等于0的值时按默认值处理。<br/>iterations默认值为1,默认播放一次,设置为其他数值时按默认值处理。<br>playMode控制动画播放模式,默认值为PlayMode.Normal,设置为其他数值时按照默认值处理。<br/>页面转场切换时,建议使用默认关闭动效。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
133| showInSubWindow<sup>10+</sup> | boolean                                  | 否    | 是   | 某弹框需要显示在主窗口之外时,是否在子窗口显示此弹窗。值为true表示在子窗口显示弹窗。<br>默认值:false,弹窗显示在应用内,而非独立子窗口。<br>**说明**:showInSubWindow为true的弹窗无法触发显示另一个showInSubWindow为true的弹窗。不建议在showInSubWindow为true的弹窗中使用CalendarPicker、CalendarPickerDialog、DatePickerDialog、TextPickerDialog、TimePickerDialog、Toast组件,弹窗会影响上述组件行为。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
134| backgroundColor<sup>10+</sup> | [ResourceColor](ts-types.md#resourcecolor)      | 否   | 是  | 设置弹窗背板填充。<br/>默认值:Color.Transparent<br />**说明:** 如果同时设置了内容构造器的背景色,则backgroundColor会被内容构造器的背景色覆盖。<br/>backgroundColor会与模糊属性backgroundBlurStyle叠加产生效果,如果不符合预期,可将backgroundBlurStyle设置为BlurStyle.NONE,即可取消模糊。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
135| cornerRadius<sup>10+</sup>    | [Dimension](ts-types.md#dimension10)&nbsp;\|&nbsp;[BorderRadiuses](ts-types.md#borderradiuses9) | 否   | 是  | 设置背板的圆角半径。<br />可分别设置4个圆角的半径。<br />默认值:{ topLeft: '32vp', topRight: '32vp', bottomLeft: '32vp', bottomRight: '32vp' }<br />**说明**:自定义弹窗默认的背板圆角半径为32vp,如果需要使用cornerRadius属性,请和[borderRadius](ts-universal-attributes-border.md#borderradius)属性一起使用。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
136| isModal<sup>11+</sup> | boolean | 否 | 是 | 弹窗是否为模态窗口。值为true表示为模态窗口且有蒙层,不可与弹窗周围其他控件进行交互,即蒙层区域无法事件透传。值为false表示为非模态窗口且无蒙层,可以与弹窗周围其他控件进行交互。<br/>默认值:true<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
137| onWillDismiss<sup>12+</sup> | Callback<[DismissDialogAction](#dismissdialogaction12)> | 否 | 是 | 交互式关闭回调函数。<br/>**说明:**<br/>1.当用户执行点击遮障层关闭、侧滑(左滑/右滑)、三键back、键盘ESC关闭交互操作时,如果注册该回调函数,则不会立刻关闭弹窗。在回调函数中可以通过reason得到阻拦关闭弹窗的操作类型,从而根据原因选择是否能关闭弹窗。当前组件返回的reason中,暂不支持CLOSE_BUTTON的枚举值。<br/>2.在onWillDismiss回调中,不能再做onWillDismiss拦截。 <br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
138| borderWidth<sup>12+</sup> | [Dimension](ts-types.md#dimension10)&nbsp;\|&nbsp;[EdgeWidths](ts-types.md#edgewidths9)  | 否 | 是 | 设置弹窗背板的边框宽度。<br />可分别设置4个边框宽度。<br />默认值:0。<br /> 百分比参数方式:以父元素弹窗宽的百分比来设置弹窗的边框宽度。<br />当弹窗左边框和右边框大于弹窗宽度,弹窗上边框和下边框大于弹窗高度,显示可能不符合预期。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
139| borderColor<sup>12+</sup> | [ResourceColor](ts-types.md#resourcecolor)&nbsp;\|&nbsp;[EdgeColors](ts-types.md#edgecolors9)  | 否 | 是 | 设置弹窗背板的边框颜色。<br/>默认值:Color.Black<br/>如果使用borderColor属性,需要和borderWidth属性一起使用。 <br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
140| borderStyle<sup>12+</sup> | [BorderStyle](ts-appendix-enums.md#borderstyle)&nbsp;\|&nbsp;[EdgeStyles](ts-types.md#edgestyles9)  | 否 | 是 | 设置弹窗背板的边框样式。<br/>默认值:BorderStyle.Solid<br/>如果使用borderStyle属性,需要和borderWidth属性一起使用。 <br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
141| width<sup>12+</sup> | [Dimension](ts-types.md#dimension10) | 否   | 是  | 设置弹窗背板的宽度。<br />**说明:**<br>- 弹窗宽度默认最大值:400vp。<br />- 百分比参数方式:弹窗参考宽度为所在窗口的宽度,在此基础上调小或调大。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
142| height<sup>12+</sup> | [Dimension](ts-types.md#dimension10)   | 否 | 是 | 设置弹窗背板的高度。<br />**说明:**<br />- 弹窗高度默认最大值:0.9 *(窗口高度 - 安全区域)。<br />- 百分比参数方式:弹窗参考高度为(窗口高度 - 安全区域),在此基础上调小或调大。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
143| shadow<sup>12+</sup> | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions对象说明)&nbsp;\|&nbsp;[ShadowStyle](ts-universal-attributes-image-effect.md#shadowstyle10枚举说明)   | 否 | 是 | 设置弹窗背板的阴影。 <br /> 当设备为2in1时,默认场景下获焦阴影值为ShadowStyle.OUTER_FLOATING_MD,失焦为ShadowStyle.OUTER_FLOATING_SM。其他设备默认无阴影。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
144| backgroundBlurStyle<sup>12+</sup> | [BlurStyle](ts-universal-attributes-background.md#blurstyle9)                 | 否   | 是  | 弹窗背板模糊材质。<br/>默认值:BlurStyle.COMPONENT_ULTRA_THICK <br/>**说明:** <br/>设置为BlurStyle.NONE即可关闭背景虚化。当设置了backgroundBlurStyle为非NONE值时,则不要设置backgroundColor,否则颜色显示将不符合预期效果。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
145| backgroundBlurStyleOptions<sup>19+</sup> | [BackgroundBlurStyleOptions](ts-universal-attributes-background.md#backgroundblurstyleoptions10对象说明) | 否 | 是 | 背景模糊效果。默认值请参考BackgroundBlurStyleOptions类型说明。<br />**原子化服务API:** 从API version 19开始,该接口支持在原子化服务中使用。 |
146| backgroundEffect<sup>19+</sup> | [BackgroundEffectOptions](ts-universal-attributes-background.md#backgroundeffectoptions11) | 否 | 是 | 背景效果参数。默认值请参考BackgroundEffectOptions类型说明。<br />**原子化服务API:** 从API version 19开始,该接口支持在原子化服务中使用。 |
147| keyboardAvoidMode<sup>12+</sup> | [KeyboardAvoidMode](ts-universal-attributes-popup.md#keyboardavoidmode12枚举说明) | 否 | 是 | 用于设置弹窗是否在拉起软键盘时进行自动避让。<br/>默认值:KeyboardAvoidMode.DEFAULT<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
148| enableHoverMode<sup>14+</sup>     | boolean | 否   | 是  | 是否响应悬停态,值为true时,响应悬停态。<br />默认值:false,默认不响应。<br/>**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。|
149| hoverModeArea<sup>14+</sup>       | [HoverModeAreaType](ts-universal-attributes-sheet-transition.md#hovermodeareatype14) | 否   | 是  | 悬停态下弹窗默认展示区域。<br />默认值:HoverModeAreaType.BOTTOM_SCREEN。<br/>**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。|
150| onWillAppear<sup>19+</sup> | Callback&lt;void&gt; | 否 | 是 | 弹窗显示动效前的事件回调。<br />**说明:**<br />1.正常时序依次为:onWillAppear>>onDidAppear>>onWillDisappear>>onDidDisappear。<br />2.在onWillAppear内设置改变弹窗显示效果的回调事件,二次弹出生效。 <br/>**原子化服务API:** 从API version 19开始,该接口支持在原子化服务中使用。|
151| onDidAppear<sup>19+</sup> | Callback&lt;void&gt; | 否 | 是 | 弹窗弹出时的事件回调。<br />**说明:**<br />1.正常时序依次为:onWillAppear>>onDidAppear>>onWillDisappear>>onDidDisappear。<br />2.在onDidAppear内设置改变弹窗显示效果的回调事件,二次弹出生效。<br />3.快速点击弹出,关闭弹窗时,onWillDisappear在onDidAppear前生效。<br/>4.弹窗入场动效未完成时彻底关闭弹窗,动效打断,onDidAppear不会触发。<br/>**原子化服务API:** 从API version 19开始,该接口支持在原子化服务中使用。 |
152| onWillDisappear<sup>19+</sup> | Callback&lt;void&gt; | 否 | 是 | 弹窗退出动效前的事件回调。<br />**说明:**<br />1.正常时序依次为:onWillAppear>>onDidAppear>>onWillDisappear>>onDidDisappear。<br /> **原子化服务API:** 从API version 19开始,该接口支持在原子化服务中使用。|
153| onDidDisappear<sup>19+</sup> | Callback&lt;void&gt; | 否 | 是 | 弹窗消失时的事件回调。<br />**说明:**<br />1.正常时序依次为:onWillAppear>>onDidAppear>>onWillDisappear>>onDidDisappear。<br/>**原子化服务API:** 从API version 19开始,该接口支持在原子化服务中使用。 |
154| keyboardAvoidDistance<sup>15+</sup>       | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | 否   | 是  | 弹窗避让键盘后,和键盘之间的距离。<br />**说明:**<br />- 默认值:16vp。<br />- 默认单位:vp。<br />- 当且仅当keyboardAvoidMode属性设置为DEFAULT时生效。<br/>**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。|
155| levelMode<sup>15+</sup>       | [LevelMode](../js-apis-promptAction.md#levelmode15枚举说明) | 否   | 是  | 设置弹窗显示层级。<br />**说明:**<br />- 默认值:LevelMode.OVERLAY。<br />- 当且仅当showInSubWindow属性设置为false时生效。<br/>**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。|
156| levelUniqueId<sup>15+</sup>       | number | 否   | 是  | 设置页面级弹窗需要显示的层级下的[节点 uniqueId](../js-apis-arkui-frameNode.md#getuniqueid12)。<br/>取值范围:大于等于0的数字。<br />**说明:**<br />- 当且仅当levelMode属性设置为LevelMode.EMBEDDED时生效。<br/>**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。|
157| immersiveMode<sup>15+</sup>       | [ImmersiveMode](../js-apis-promptAction.md#immersivemode15枚举说明) | 否   | 是  | 设置页面内弹窗蒙层效果。<br />**说明:**<br />- 默认值:ImmersiveMode.DEFAULT <br />- 当且仅当levelMode属性设置为LevelMode.EMBEDDED时生效。<br/>**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。|
158| levelOrder<sup>18+</sup>       | [LevelOrder](../js-apis-promptAction.md#levelorder18) | 否   | 是  | 设置弹窗显示的顺序。<br />**说明:**<br />- 默认值:LevelOrder.clamp(0) <br />- 不支持动态刷新顺序。<br/>**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。|
159| focusable<sup>19+</sup>       | boolean | 否   | 是  | 设置弹窗是否获取焦点。值为true表示获取焦点,值为false表示不获取焦点。<br />默认值:true <br />**说明:**<br />只有弹出覆盖在当前窗口之上的弹窗才可以获取焦点。<br/>**原子化服务API:** 从API version 19开始,该接口支持在原子化服务中使用。|
160
161> **说明:**
162>
163> - 按下返回键和ESC键时会让弹窗退出。
164> - 弹窗在避让软键盘时到达极限高度之后会压缩高度。
165>   需要注意:高度压缩生效在外层容器上,如果容器根节点中的子组件设置了较大的固定高度,由于容器默认不裁剪,依然可能存在超出屏幕显示的情况。
166> - 自定义弹窗仅适用于简单提示场景,不能替代页面使用。弹窗避让软键盘时,与软键盘之间存在16vp的安全间距。
167> - 为了达成良好的视觉体验,弹窗的显示和关闭存在默认动画,动画时长不同设备间可能存在差异。
168>   需要注意:在动画播放过程中,页面不响应触摸、滑动、点击操作。关闭默认弹窗动画效果可设置openAnimation和closeAnimation的duration为0。
169> - 当前,ArkUI弹出框默认为非页面级弹出框,在页面路由跳转时,如果开发者未调用close方法将其关闭,弹出框将不会自动关闭。若需实现在跳转页面时覆盖弹出框的场景,可以使用[组件导航子页面显示类型的弹窗类型](../../../ui/arkts-navigation-navigation.md#页面显示类型)或者[页面级弹出框](../../../ui/arkts-embedded-dialog.md)。
170
171## DismissDialogAction<sup>12+</sup>
172
173Dialog关闭的信息。
174
175**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
176
177**系统能力:** SystemCapability.ArkUI.ArkUI.Full
178
179### 属性
180
181| 名称    | 类型                                                         | 只读 | 可选 | 说明                                                         |
182| ------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
183| dismiss | Callback&lt;void&gt;                                         | 否   | 否   | Dialog关闭回调函数。开发者需要退出时调用,不需要退出时无需调用。 |
184| reason  | [DismissReason](ts-universal-attributes-popup.md#dismissreason12枚举说明) | 否   | 否   | Dialog无法关闭原因。根据开发者需要选择不同操作下,Dialog是否需要关闭。 |
185
186## 示例
187
188### 示例1(弹出嵌套弹窗)
189
190该示例实现了在CustomDialog中打开另一个或另一些CustomDialog。
191
192```ts
193// xxx.ets
194@CustomDialog
195struct CustomDialogExampleTwo {
196  controllerTwo?: CustomDialogController;
197  build() {
198    Column() {
199      Text('我是第二个弹窗')
200        .fontSize(30)
201        .height(100)
202      Button('点我关闭第二个弹窗')
203        .onClick(() => {
204          if (this.controllerTwo != undefined) {
205            this.controllerTwo.close();
206          }
207        })
208        .margin(20)
209    }
210  }
211}
212@CustomDialog
213@Component
214struct CustomDialogExample {
215  @Link textValue: string;
216  @Link inputValue: string;
217  dialogControllerTwo: CustomDialogController | null = new CustomDialogController({
218    builder: CustomDialogExampleTwo(),
219    alignment: DialogAlignment.Bottom,
220    onWillDismiss:(dismissDialogAction: DismissDialogAction)=> {
221      console.info(`reason= ${dismissDialogAction.reason}`);
222      console.info('dialog onWillDismiss');
223      if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
224        dismissDialogAction.dismiss();
225      }
226      if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
227        dismissDialogAction.dismiss();
228      }
229    },
230    offset: { dx: 0, dy: -25 } })
231  controller?: CustomDialogController;
232  // 若尝试在CustomDialog中传入多个其他的Controller,以实现在CustomDialog中打开另一个或另一些CustomDialog,那么此处需要将指向自己的controller放在所有controller的后面
233  cancel: () => void = () => {
234  }
235  confirm: () => void = () => {
236  }
237
238  build() {
239    Column() {
240      Text('Change text').fontSize(20).margin({ top: 10, bottom: 10 })
241      TextInput({ placeholder: '', text: this.textValue }).height(60).width('90%')
242        .onChange((value: string) => {
243          this.textValue = value;
244        })
245      Text('Whether to change a text?').fontSize(16).margin({ bottom: 10 })
246      Flex({ justifyContent: FlexAlign.SpaceAround }) {
247        Button('cancel')
248          .onClick(() => {
249            if (this.controller != undefined) {
250              this.controller.close();
251              this.cancel();
252            }
253          }).backgroundColor(0xffffff).fontColor(Color.Black)
254        Button('confirm')
255          .onClick(() => {
256            if (this.controller != undefined) {
257              this.inputValue = this.textValue;
258              this.controller.close();
259              this.confirm();
260            }
261          }).backgroundColor(0xffffff).fontColor(Color.Red)
262      }.margin({ bottom: 10 })
263
264      Button('点我打开第二个弹窗')
265        .onClick(() => {
266          if (this.dialogControllerTwo != null) {
267            this.dialogControllerTwo.open();
268          }
269        })
270        .margin(20)
271    }.borderRadius(10)
272    // 如果需要使用border属性或cornerRadius属性,请和borderRadius属性一起使用。
273  }
274}
275@Entry
276@Component
277struct CustomDialogUser {
278  @State textValue: string = ''
279  @State inputValue: string = 'click me'
280  dialogController: CustomDialogController | null = new CustomDialogController({
281    builder: CustomDialogExample({
282      cancel: ()=> { this.onCancel(); },
283      confirm: ()=> { this.onAccept(); },
284      textValue: this.textValue,
285      inputValue: this.inputValue
286    }),
287    cancel: this.exitApp,
288    autoCancel: true,
289    onWillDismiss:(dismissDialogAction: DismissDialogAction)=> {
290      console.info(`reason= ${dismissDialogAction.reason}`);
291      console.info('dialog onWillDismiss');
292      if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
293        dismissDialogAction.dismiss();
294      }
295      if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
296        dismissDialogAction.dismiss();
297      }
298    },
299    alignment: DialogAlignment.Bottom,
300    offset: { dx: 0, dy: -20 },
301    gridCount: 4,
302    customStyle: false,
303    cornerRadius: 10,
304  })
305
306  // 在自定义组件即将析构销毁时将dialogController置空
307  aboutToDisappear() {
308    this.dialogController = null; // 将dialogController置空
309  }
310
311  onCancel() {
312    console.info('Callback when the first button is clicked');
313  }
314
315  onAccept() {
316    console.info('Callback when the second button is clicked');
317  }
318
319  exitApp() {
320    console.info('Click the callback in the blank area');
321  }
322  build() {
323    Column() {
324      Button(this.inputValue)
325        .onClick(() => {
326          if (this.dialogController != null) {
327            this.dialogController.open();
328          }
329        }).backgroundColor(0x317aff)
330    }.width('100%').margin({ top: 5 })
331  }
332}
333```
334
335![zh-cn_image_custom](figures/zh-cn_image_custom.gif)
336
337### 示例2(可在主窗外弹出的弹窗)
338
339在2in1设备上设置showInSubWindow为true时,可以弹出在主窗外显示的弹窗。
340
341```ts
342// xxx.ets
343@CustomDialog
344struct CustomDialogExample {
345  controller?: CustomDialogController;
346  cancel: () => void = () => {
347  }
348  confirm: () => void = () => {
349  }
350  build() {
351    Column() {
352      Text('可展示在主窗口外的弹窗')
353        .fontSize(30)
354        .height(100)
355      Button('点我关闭弹窗')
356        .onClick(() => {
357          if (this.controller != undefined) {
358            this.controller.close();
359          }
360        })
361        .margin(20)
362    }
363  }
364}
365@Entry
366@Component
367struct CustomDialogUser {
368  dialogController: CustomDialogController | null = new CustomDialogController({
369    builder: CustomDialogExample({
370      cancel: ()=> { this.onCancel(); },
371      confirm: ()=> { this.onAccept(); }
372    }),
373    cancel: this.existApp,
374    autoCancel: true,
375    onWillDismiss:(dismissDialogAction: DismissDialogAction)=> {
376      console.info(`reason= ${dismissDialogAction.reason}`);
377      console.info('dialog onWillDismiss');
378      if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
379        dismissDialogAction.dismiss();
380      }
381      if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
382        dismissDialogAction.dismiss();
383      }
384    },
385    alignment: DialogAlignment.Center,
386    offset: { dx: 0, dy: -20 },
387    gridCount: 4,
388    showInSubWindow: true,
389    isModal: true,
390    customStyle: false,
391    cornerRadius: 10,
392    focusable: true
393  })
394  // 在自定义组件即将析构销毁时将dialogController置空
395  aboutToDisappear() {
396    this.dialogController = null; // 将dialogController置空
397  }
398
399  onCancel() {
400    console.info('Callback when the first button is clicked');
401  }
402
403  onAccept() {
404    console.info('Callback when the second button is clicked');
405  }
406
407  existApp() {
408    console.info('Click the callback in the blank area');
409  }
410
411  build() {
412    Column() {
413      Button('click me')
414        .onClick(() => {
415          if (this.dialogController != null) {
416            this.dialogController.open();
417          }
418        }).backgroundColor(0x317aff)
419    }.width('100%').margin({ top: 5 })
420  }
421}
422```
423
424![zh-cn_image_custom-showinsubwindow](figures/zh-cn_image_custom-showinsubwindow.jpg)
425
426### 示例3(设置弹窗的样式)
427该示例定义了CustomDialog的样式,包括宽度、高度、背景色、阴影等。
428```ts
429// xxx.ets
430@CustomDialog
431struct CustomDialogExample {
432  controller?: CustomDialogController;
433  cancel: () => void = () => {
434  }
435  confirm: () => void = () => {
436  }
437  build() {
438    Column() {
439      Text('这是自定义弹窗')
440        .fontSize(30)
441        .height(100)
442      Button('点我关闭弹窗')
443        .onClick(() => {
444          if (this.controller != undefined) {
445            this.controller.close();
446          }
447        })
448        .margin(20)
449    }
450  }
451}
452@Entry
453@Component
454struct CustomDialogUser {
455  dialogController: CustomDialogController | null = new CustomDialogController({
456    builder: CustomDialogExample({
457      cancel: ()=> { this.onCancel(); },
458      confirm: ()=> { this.onAccept(); }
459    }),
460    cancel: this.existApp,
461    autoCancel: true,
462    onWillDismiss:(dismissDialogAction: DismissDialogAction)=> {
463      console.info(`reason= ${dismissDialogAction.reason}`);
464      console.info('dialog onWillDismiss')
465      if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
466        dismissDialogAction.dismiss();
467      }
468      if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
469        dismissDialogAction.dismiss();
470      }
471    },
472    alignment: DialogAlignment.Center,
473    offset: { dx: 0, dy: -20 },
474    customStyle: false,
475    cornerRadius: 20,
476    width: 300,
477    height: 200,
478    borderWidth: 1,
479    borderStyle: BorderStyle.Dashed,//使用borderStyle属性,需要和borderWidth属性一起使用
480    borderColor: Color.Blue,//使用borderColor属性,需要和borderWidth属性一起使用
481    backgroundColor: Color.White,
482    shadow: ({ radius: 20, color: Color.Grey, offsetX: 50, offsetY: 0}),
483  })
484  // 在自定义组件即将析构销毁时将dialogController置空
485  aboutToDisappear() {
486    this.dialogController = null; // 将dialogController置空
487  }
488
489  onCancel() {
490    console.info('Callback when the first button is clicked');
491  }
492
493  onAccept() {
494    console.info('Callback when the second button is clicked');
495  }
496
497  existApp() {
498    console.info('Click the callback in the blank area');
499  }
500
501  build() {
502    Column() {
503      Button('click me')
504        .onClick(() => {
505          if (this.dialogController != null) {
506            this.dialogController.open();
507          }
508        }).backgroundColor(0x317aff)
509    }.width('100%').margin({ top: 5 })
510  }
511}
512```
513
514![zh-cn_image_custom_style](figures/zh-cn_image_custom_style.gif)
515
516### 示例4(悬停态弹窗)
517
518<!--RP1-->该示例展示了在悬停态下设置dialog布局区域的效果。<!--RP1End-->
519
520```ts
521@CustomDialog
522@Component
523struct CustomDialogExample {
524  @Link textValue: string;
525  @Link inputValue: string;
526  controller?: CustomDialogController;
527
528  build() {
529    Column() {
530      Text('Change text').fontSize(20).margin({ top: 10, bottom: 10 })
531      TextInput({ placeholder: '', text: this.textValue }).height(60).width('90%')
532        .onChange((value: string) => {
533          this.textValue = value;
534        })
535      Text('Whether to change a text?').fontSize(16).margin({ bottom: 10 })
536      Flex({ justifyContent: FlexAlign.SpaceAround }) {
537        Button('cancel')
538          .onClick(() => {
539            if (this.controller != undefined) {
540              this.controller.close();
541            }
542          }).backgroundColor(0xffffff).fontColor(Color.Black)
543        Button('confirm')
544          .onClick(() => {
545            if (this.controller != undefined) {
546              this.inputValue = this.textValue;
547              this.controller.close();
548            }
549          }).backgroundColor(0xffffff).fontColor(Color.Red)
550      }.margin({ bottom: 10 })
551    }.borderRadius(10)
552    // 如果需要使用border属性或cornerRadius属性,请和borderRadius属性一起使用。
553  }
554}
555@Entry
556@Component
557struct CustomDialogUser {
558  @State textValue: string = '';
559  @State inputValue: string = 'click me';
560  dialogController: CustomDialogController | null = new CustomDialogController({
561    builder: CustomDialogExample({
562      textValue: this.textValue,
563      inputValue: this.inputValue
564    }),
565    cancel: this.exitApp,
566    autoCancel: true,
567    onWillDismiss: (dismissDialogAction: DismissDialogAction)=> {
568      console.info(`reason= ${dismissDialogAction.reason}`);
569      console.info('dialog onWillDismiss');
570      if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
571        dismissDialogAction.dismiss();
572      }
573      if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
574        dismissDialogAction.dismiss();
575      }
576    },
577    alignment: DialogAlignment.Bottom,
578    offset: { dx: 0, dy: -20 },
579    gridCount: 4,
580    customStyle: false,
581    cornerRadius: 10,
582    enableHoverMode: true,
583    hoverModeArea: HoverModeAreaType.TOP_SCREEN
584  })
585
586  // 在自定义组件即将析构销毁时将dialogController置空
587  aboutToDisappear() {
588    this.dialogController = null; // 将dialogController置空
589  }
590
591  exitApp() {
592    console.info('Click the callback in the blank area');
593  }
594
595  build() {
596    Column() {
597      Button(this.inputValue)
598        .onClick(() => {
599          if (this.dialogController != null) {
600            this.dialogController.open();
601          }
602        }).backgroundColor(0x317aff)
603    }.width('100%').margin({ top: 5 })
604  }
605}
606```
607
608<!--RP2--><!--RP2End-->
609
610### 示例5(获取弹窗的状态)
611
612该示例实现了在CustomDialogController中调用getState获取弹窗当前状态。
613
614```ts
615// xxx.ets
616@CustomDialog
617struct CustomDialogExample {
618  controller?: CustomDialogController
619
620  build() {
621    Column() {
622      Button("点我查询弹窗状态:通过自定义组件自带controller")
623        .onClick(() => {
624          if (this.getDialogController() != undefined) {
625            console.info('state:' + this.getDialogController().getState())
626          } else {
627            console.info('state: no exist')
628          }
629        }).margin(20)
630      Button('点我查询弹窗状态:通过CustomDialogController ')
631        .onClick(() => {
632          console.info('state:' + this.controller?.getState())
633        }).margin(20)
634      Button('点我关闭弹窗')
635        .onClick(() => {
636          if (this.getDialogController() != undefined) {
637            this.getDialogController().close()
638          }
639        }).margin(20)
640
641    }
642  }
643}
644
645@Entry
646@Component
647struct CustomDialogUser {
648  @State bg: ResourceColor = Color.Green
649  dialogController: CustomDialogController | null = new CustomDialogController({
650    builder: CustomDialogExample({
651    }),
652    autoCancel: false
653  })
654
655  build() {
656    Column() {
657      Button('click me')
658        .onClick(() => {
659          if (this.dialogController != null) {
660            this.dialogController.open()
661          }
662        }).backgroundColor(0x317aff)
663    }.width('100%').margin({ top: 5 })
664    .backgroundColor(this.bg)
665  }
666}
667```
668
669### 示例6(使用@Link和@Consume监听数据变化)
670
671该示例使用@Link和@Consume实现页面与弹窗内数据的双向绑定。
672
673```ts
674@CustomDialog
675@Component
676struct CustomDialogExample {
677  @Link textValue: string;
678  @Consume inputValue: string;
679  controller?: CustomDialogController;
680
681  cancel: () => void = () => {
682  }
683  confirm: () => void = () => {
684  }
685
686  build() {
687    Column() {
688      Text('Change text').fontSize(20).margin({ top: 10, bottom: 10 })
689      TextInput({ placeholder: '', text: this.textValue }).height(60).width('90%')
690        .onChange((value: string) => {
691          this.textValue = value;
692        })
693      Text('Whether to change a text?').fontSize(16).margin({ bottom: 10 })
694      Flex({ justifyContent: FlexAlign.SpaceAround }) {
695        Button('cancel')
696          .onClick(() => {
697            if (this.controller != undefined) {
698              this.controller.close();
699              this.cancel();
700            }
701          }).backgroundColor(0xffffff).fontColor(Color.Black)
702        Button('confirm')
703          .onClick(() => {
704            if (this.controller != undefined) {
705              this.inputValue = this.textValue;
706              this.controller.close();
707              this.confirm();
708            }
709          }).backgroundColor(0xffffff).fontColor(Color.Red)
710      }.margin({ bottom: 10 })
711    }.borderRadius(10)
712  }
713}
714@Entry
715@Component
716struct CustomDialogUser {
717  @State textValue: string = ''
718  @Provide inputValue: string = 'click me'
719  dialogController: CustomDialogController | null = new CustomDialogController({
720    builder: CustomDialogExample({
721      cancel: ()=> { this.onCancel(); },
722      confirm: ()=> { this.onAccept(); },
723      textValue: this.textValue
724    }),
725    cancel: this.exitApp,
726    autoCancel: true,
727    onWillDismiss:(dismissDialogAction: DismissDialogAction)=> {
728      if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
729        dismissDialogAction.dismiss();
730      }
731      if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
732        dismissDialogAction.dismiss();
733      }
734    },
735    alignment: DialogAlignment.Center,
736    offset: { dx: 0, dy: -20 },
737    gridCount: 4,
738    customStyle: false,
739    cornerRadius: 10,
740  })
741
742  // 在自定义组件即将析构销毁时将dialogController置空
743  aboutToDisappear() {
744    this.dialogController = null; // 将dialogController置空
745  }
746
747  onCancel() {
748    console.info('Callback when the first button is clicked');
749  }
750
751  onAccept() {
752    console.info('Callback when the second button is clicked');
753  }
754
755  exitApp() {
756    console.info('Click the callback in the blank area');
757  }
758  build() {
759    Column() {
760      Button(this.inputValue)
761        .onClick(() => {
762          if (this.dialogController != null) {
763            this.dialogController.open();
764          }
765        }).backgroundColor(0x317aff)
766    }.width('100%').margin({ top: 5 })
767  }
768}
769```
770![zh-cn_image_custom](figures/dialog_consume_or_link.gif)
771
772### 示例7(自定义带loading的弹窗)
773
774该示例使用maskColor,maskRect和LoadingProgress,实现带loading的弹窗,并展示不在maskRect区域的事件透传效果。
775
776```ts
777import window from '@ohos.window';
778
779@CustomDialog
780@Component
781struct LoadingDialogExample {
782  controller?: CustomDialogController;
783  cancel: () => void = () => {
784  }
785  confirm: () => void = () => {
786  }
787
788  build() {
789    Column() {
790      LoadingProgress().color(Color.Blue).layoutWeight(1)
791    }.borderRadius(10).width(100).height(100)
792  }
793}
794
795@Entry
796@Component
797struct CustomDialogUser {
798  @State number: number = 0;
799  dialogController: CustomDialogController | null = null;
800
801  // 在自定义组件即将析构销毁时将dialogController置空
802  aboutToDisappear() {
803    this.dialogController = null; // 将dialogController置空
804  }
805
806  onCancel() {
807    console.info('Callback when the first button is clicked');
808  }
809
810  onAccept() {
811    console.info('Callback when the second button is clicked');
812  }
813
814  exitApp() {
815    console.info('Click the callback in the blank area');
816  }
817
818  build() {
819    Column() {
820      Button("click " + this.number).onClick(() => {
821        this.number++;
822      })
823      Button("show loading dialog").onClick(() => {
824        //获取窗口对象
825        let windowClass = window.getLastWindow(this.getUIContext().getHostContext());
826        windowClass.then(window => {
827          //获取窗口信息,设置maskRect
828          let properties = window.getWindowProperties();
829          let maskRect = {
830            x: this.getUIContext().px2vp(properties.windowRect.left + 150),
831            y: this.getUIContext().px2vp(properties.windowRect.top + 350),
832            width: this.getUIContext().px2vp(properties.windowRect.width - 300),
833            height: this.getUIContext().px2vp(properties.windowRect.height - 700)
834          } as Rectangle
835          if (this.dialogController == null) {
836            this.dialogController = new CustomDialogController({
837              builder: LoadingDialogExample({
838                cancel: () => {
839                  this.onCancel();
840                },
841                confirm: () => {
842                  this.onAccept();
843                },
844              }),
845              cancel: this.exitApp,
846              maskRect: maskRect,
847              autoCancel: false,
848              maskColor: "#33AA0000",
849              showInSubWindow: false,
850              backgroundBlurStyle: BlurStyle.NONE,
851              onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
852                if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
853                  dismissDialogAction.dismiss();
854                }
855                if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
856                  dismissDialogAction.dismiss();
857                }
858              },
859              alignment: DialogAlignment.Center,
860              customStyle: false,
861              cornerRadius: 10,
862              openAnimation: { duration: 0, tempo: 0 },
863              closeAnimation: { duration: 0, tempo: 0 }
864            })
865          }
866          this.dialogController.close();
867          this.dialogController.open();
868        })
869      }).backgroundColor(0x317aff)
870    }.width('100%').margin({ top: 5 })
871  }
872}
873```
874![zh-cn_image_custom](figures/custom_loading_dialog.gif)
875
876### 示例8(不使用keyboardAvoidDistance调整弹窗与软键盘的间距)
877
878该示例通过监听键盘变化,调整布局margin的bottom,实现与使用keyboardAvoidDistance调整弹窗与软键盘的间距一样的效果。
879
880```ts
881import window from '@ohos.window';
882
883@CustomDialog
884@Component
885struct CustomDialogExample {
886  @Link textValue: string;
887  @Link inputValue: string;
888  @Link isKeyboardShow: boolean
889  @Link navigationBarHeight: number
890  controller?: CustomDialogController;
891  cancel: () => void = () => {
892  }
893  confirm: () => void = () => {
894  }
895
896  build() {
897    Column() {
898      Text('Change text').fontSize(20).margin({ top: 10, bottom: 10 })
899      TextInput({ placeholder: '', text: this.textValue }).height(60).width('90%')
900        .onChange((value: string) => {
901          this.textValue = value;
902        })
903      Text('Whether to change a text?').fontSize(16).margin({ bottom: 10 })
904      Flex({ justifyContent: FlexAlign.SpaceAround }) {
905        Button('cancel')
906          .onClick(() => {
907            if (this.controller != undefined) {
908              this.controller.close();
909              this.cancel();
910            }
911          }).backgroundColor(0xffffff).fontColor(Color.Black)
912        Button('confirm')
913          .onClick(() => {
914            if (this.controller != undefined) {
915              this.inputValue = this.textValue;
916              this.controller.close();
917              this.confirm();
918            }
919          }).backgroundColor(0xffffff).fontColor(Color.Red)
920      }.margin({ bottom: 10 })
921    }.borderRadius(10)
922    .margin({
923      // 通过键盘显隐调整间距(键盘与弹窗间距为16vp)
924      bottom: this.isKeyboardShow ? -16 : this.navigationBarHeight
925    }).backgroundColor(Color.White)
926  }
927}
928
929@Entry
930@Component
931struct CustomDialogUser {
932  @State textValue: string = ''
933  @State inputValue: string = 'click me'
934  @State isKeyboardShow: boolean = false
935  @State navigationBarHeight: number = 0
936  windowClass: window.Window | null = null
937  dialogController: CustomDialogController | null = new CustomDialogController({
938    builder: CustomDialogExample({
939      cancel: () => {
940        this.onCancel();
941      },
942      confirm: () => {
943        this.onAccept();
944      },
945      textValue: this.textValue,
946      inputValue: this.inputValue,
947      isKeyboardShow: this.isKeyboardShow,
948      navigationBarHeight: this.navigationBarHeight
949    }),
950    cancel: this.exitApp,
951    autoCancel: true,
952    onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
953      if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
954        dismissDialogAction.dismiss();
955      }
956      if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
957        dismissDialogAction.dismiss();
958      }
959    },
960    alignment: DialogAlignment.Bottom,
961    customStyle: true,
962    cornerRadius: 10,
963  })
964
965  aboutToAppear(): void {
966    let windowClass = window.getLastWindow(this.getUIContext().getHostContext());
967    windowClass.then(win => {
968      this.windowClass = win;
969      // 获取底部导航栏高度
970      let navigationArea = this.windowClass?.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
971      this.navigationBarHeight = navigationArea.bottomRect.height;
972      this.windowClass?.on('avoidAreaChange', (data) => {
973        if (data.type == window.AvoidAreaType.TYPE_KEYBOARD) {
974          this.isKeyboardShow = data.area.bottomRect.height > 0;
975        }
976      })
977    });
978  }
979
980  // 在自定义组件即将析构销毁时将dialogController置空
981  aboutToDisappear() {
982    this.dialogController = null; // 将dialogController置空
983    this.windowClass?.off('avoidAreaChange')
984  }
985
986  onCancel() {
987    console.info('Callback when the first button is clicked');
988  }
989
990  onAccept() {
991    console.info('Callback when the second button is clicked');
992  }
993
994  exitApp() {
995    console.info('Click the callback in the blank area');
996  }
997
998  build() {
999    Column() {
1000      Button(this.inputValue)
1001        .onClick(() => {
1002          if (this.dialogController != null) {
1003            this.dialogController.open();
1004          }
1005        }).backgroundColor(0x317aff)
1006    }.width('100%').margin({ top: 5 })
1007  }
1008}
1009```
1010![zh-cn_image_custom](figures/dialog_keyboard_distance.gif)
1011
1012### 示例9(弹窗生命周期)
1013
1014该示例展示了弹窗生命周期的相关接口的使用方法。
1015
1016```ts
1017// xxx.ets
1018@CustomDialog
1019struct CustomDialogExample1 {
1020  controller?: CustomDialogController
1021  cancel: () => void = () => {
1022  }
1023  confirm: () => void = () => {
1024  }
1025  build() {
1026    Column() {
1027      Text('允许访问相机?')
1028        .fontSize(30)
1029        .height(100)
1030      Button('点我关闭弹窗')
1031        .onClick(() => {
1032          if (this.controller != undefined) {
1033            this.controller.close();
1034          }
1035        })
1036        .margin(20)
1037    }
1038  }
1039}
1040
1041@Entry
1042@Component
1043struct Example3 {
1044  @State log: string = 'Log information:';
1045  dialogController: CustomDialogController | null = new CustomDialogController({
1046    builder: CustomDialogExample1({
1047      cancel: ()=> { this.onCancel(); },
1048      confirm: ()=> { this.onAccept(); }
1049    }),
1050    cancel: this.existApp,
1051    autoCancel: true,
1052    alignment: DialogAlignment.Bottom,
1053    onWillDismiss:(dismissDialogAction: DismissDialogAction)=> {
1054      console.info(`reason= ${dismissDialogAction.reason}`);
1055      console.info('dialog onWillDismiss');
1056      if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
1057        dismissDialogAction.dismiss();
1058      }
1059      if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
1060        dismissDialogAction.dismiss();
1061      }
1062    },
1063    onDidAppear: () => {
1064      this.log += '# onDidAppear';
1065      console.info('CustomDialog,is onDidAppear!');
1066    },
1067    onDidDisappear: () => {
1068      this.log += '# onDidDisappear';
1069      console.info('CustomDialog,is onDidDisappear!');
1070    },
1071    onWillAppear: () => {
1072      this.log = 'Log information:onWillAppear';
1073      console.info('CustomDialog,is onWillAppear!');
1074    },
1075    onWillDisappear: () => {
1076      this.log += '# onWillDisappear';
1077      console.info('CustomDialog,is onWillDisappear!');
1078    },
1079    offset: { dx: 0, dy: -20 },
1080    customStyle: false,
1081  })
1082  onCancel() {
1083    console.info('CustomDialog Callback when the first button is clicked');
1084  }
1085
1086  onAccept() {
1087    console.info('CustomDialog Callback when the second button is clicked');
1088  }
1089
1090  existApp() {
1091    console.info('CustomDialog Click the callback in the blank area');
1092  }
1093  build() {
1094    Column({ space: 5 }) {
1095      Button('CustomDialog')
1096        .onClick(() => {
1097          this.dialogController?.open();
1098        })
1099      Text(this.log).fontSize(30).margin({ top: 200 })
1100    }.width('100%').margin({ top: 5 })
1101  }
1102}
1103```
1104
1105![zh-cn_image_custom_lifecycle](figures/zh-cn_image_custom_lifecycle.gif)
1106
1107### 示例10(不同customStyle下的弹窗示例)
1108
1109该示例是在对齐方式为DialogAlignment.Bottom时,展示customStyle不同值下,弹窗内容与安全区域的效果。
1110
1111```ts
1112@CustomDialog
1113@Component
1114struct CustomStyleDialogExample {
1115  controller?: CustomDialogController;
1116  cancel: () => void = () => {
1117  }
1118  confirm: () => void = () => {
1119  }
1120
1121  build() {
1122    Column().borderRadius(10).width(110).height(110).backgroundColor("#2787d9")
1123  }
1124}
1125
1126@Entry
1127@Component
1128struct CustomDialogUser {
1129  @State customStyle: boolean = false;
1130  dialogController: CustomDialogController | null = null;
1131
1132  // 在自定义组件即将析构销毁时将dialogController置空
1133  aboutToDisappear() {
1134    this.dialogController = null; // 将dialogController置空
1135  }
1136
1137  onCancel() {
1138    console.info('Callback when the first button is clicked');
1139  }
1140
1141  onAccept() {
1142    console.info('Callback when the second button is clicked');
1143  }
1144
1145  exitApp() {
1146    console.info('Click the callback in the blank area');
1147  }
1148
1149  build() {
1150    Column() {
1151      Button('change  customStyle:' + this.customStyle).onClick(() => {
1152        this.customStyle = !this.customStyle;
1153      })
1154      Button('show dialog').onClick(() => {
1155        if (this.dialogController != null) {
1156          this.dialogController.close();
1157        }
1158        this.dialogController = new CustomDialogController({
1159          builder: CustomStyleDialogExample({
1160            cancel: () => {
1161              this.onCancel();
1162            },
1163            confirm: () => {
1164              this.onAccept();
1165            },
1166          }),
1167          cancel: this.exitApp,
1168          autoCancel: true,
1169          showInSubWindow: false,
1170          onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
1171            if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
1172              dismissDialogAction.dismiss();
1173            }
1174            if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
1175              dismissDialogAction.dismiss();
1176            }
1177          },
1178          alignment: DialogAlignment.Bottom,
1179          customStyle: this.customStyle,
1180          cornerRadius: 10,
1181          openAnimation: { duration: 0, tempo: 0 },
1182          closeAnimation: { duration: 0, tempo: 0 }
1183        })
1184        this.dialogController.open();
1185      }).margin({ top: 5 })
1186    }.width('100%').margin({ top: 5 })
1187  }
1188}
1189```
1190![zh-cn_image_custom](figures/customstyle_dialog_demo.gif)
1191
1192### 示例11(自定义背景模糊效果参数)
1193
1194从API version 19开始,该示例通过配置[backgroundBlurStyleOptions](#customdialogcontrolleroptions对象说明),实现自定义背景模糊效果。
1195
1196```ts
1197@CustomDialog
1198struct CustomDialogExample {
1199  controller?: CustomDialogController;
1200
1201  build() {
1202    Column() {
1203      Text('这是自定义弹窗')
1204        .fontSize(30)
1205        .height(100)
1206      Button('点我关闭弹窗')
1207        .onClick(() => {
1208          if (this.controller != undefined) {
1209            this.controller.close();
1210          }
1211        })
1212        .margin(20)
1213    }
1214  }
1215}
1216
1217@Entry
1218@Component
1219struct CustomDialogUser {
1220  dialogController: CustomDialogController | null = new CustomDialogController({
1221    builder: CustomDialogExample(),
1222    backgroundColor: undefined,
1223    backgroundBlurStyle: BlurStyle.Thin,
1224    backgroundBlurStyleOptions: {
1225      colorMode: ThemeColorMode.LIGHT,
1226      adaptiveColor: AdaptiveColor.AVERAGE,
1227      scale: 1,
1228      blurOptions: { grayscale: [20, 20] },
1229    },
1230  })
1231
1232  build() {
1233    Stack({ alignContent: Alignment.Top }) {
1234      // $r('app.media.bg')需要替换为开发者所需的图像资源文件。
1235      Image($r('app.media.bg'))
1236      Column() {
1237        Button('CustomDialog')
1238          .margin(20)
1239          .onClick(() => {
1240            if (this.dialogController != null) {
1241              this.dialogController.open();
1242            }
1243          })
1244      }.width('100%')
1245    }
1246  }
1247}
1248```
1249
1250![zh-cn_image_custom-backgroundBlurStyleOptions](figures/zh-cn_image_custom-backgroundBlurStyleOptions.png)
1251
1252### 示例12(自定义背景效果参数)
1253
1254从API version 19开始,该示例通过配置[backgroundEffect](#customdialogcontrolleroptions对象说明),实现自定义背景效果。
1255
1256```ts
1257@CustomDialog
1258struct CustomDialogExample {
1259  controller?: CustomDialogController;
1260
1261  build() {
1262    Column() {
1263      Text('这是自定义弹窗')
1264        .fontSize(30)
1265        .height(100)
1266      Button('点我关闭弹窗')
1267        .onClick(() => {
1268          if (this.controller != undefined) {
1269            this.controller.close();
1270          }
1271        })
1272        .margin(20)
1273    }
1274  }
1275}
1276
1277@Entry
1278@Component
1279struct CustomDialogUser {
1280  dialogController: CustomDialogController | null = new CustomDialogController({
1281    builder: CustomDialogExample(),
1282    backgroundColor: undefined,
1283    backgroundBlurStyle: BlurStyle.Thin,
1284    backgroundEffect: {
1285      radius: 60,
1286      saturation: 0,
1287      brightness: 1,
1288      color: Color.White,
1289      blurOptions: { grayscale: [20, 20] }
1290    },
1291  })
1292
1293  build() {
1294    Stack({ alignContent: Alignment.Top }) {
1295      // $r('app.media.bg')需要替换为开发者所需的图像资源文件。
1296      Image($r('app.media.bg'))
1297      Column() {
1298        Button('CustomDialog')
1299          .margin(20)
1300          .onClick(() => {
1301            if (this.dialogController != null) {
1302              this.dialogController.open();
1303            }
1304          })
1305      }.width('100%')
1306    }
1307  }
1308}
1309```
1310
1311![zh-cn_image_custom-backgroundEffect](figures/zh-cn_image_custom-backgroundEffect.png)