鴻蒙應用開發從入門到實戰(二十一):ArkUI自定義彈窗組件
大家好,我是潘Sir,持續分享IT技術,幫你少走彎路。《鴻蒙應用開發從入門到項目實戰》系列文章持續更新中,陸續更新AI+編程、企業級項目實戰等原創內容、歡迎關注!
上一篇文章講述了ArkUI提供的各種內置彈窗組件,當項目中遇到這些組件仍然不滿足需求時,可以使用自定義彈窗組件。本文研究自定義彈窗組件的使用。
一、概述
當現有組件不滿足要求時,可考慮自定義彈窗,自定義彈窗允許開發者自定義彈窗內容和樣式。例如

示例代碼
pages/component/dialog/新建CustomDialogPage.ets文件
@Entry
@Component
struct CustomDialogPage {
@State answer: string = '?'
controller: CustomDialogController = new CustomDialogController({
builder: TextInputDialog({
confirm: (value) => {
this.answer = value;
}
}),
alignment: DialogAlignment.Bottom,
offset: { dx: 0, dy: -30 }
})
build() {
Column({ space: 50 }) {
Row() {
Text('1+1=')
.fontWeight(FontWeight.Bold)
.fontSize(30)
Text(this.answer)
.fontWeight(FontWeight.Bold)
.fontSize(30)
}
Button('作答')
.onClick(() => {
this.controller.open();
})
}.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
@CustomDialog
struct TextInputDialog {
controller: CustomDialogController = new CustomDialogController({ builder: TextInputDialog() })
confirm: (value: string) => void;
value: string = '';
build() {
Column({ space: 20 }) {
Text('請輸入你的答案')
TextInput({ placeholder: '請輸入數字' })
.type(InputType.Number)
.onChange((value) => {
this.value = value;
})
Row({ space: 50 }) {
Button('取消')
.onClick(() => {
this.controller.close();
})
Button('確認').onClick(() => {
this.confirm(this.value);
this.controller.close();
})
}
}.padding(20)
}
}
二、使用說明
顯示自定義彈窗需要使用CustomDialogController
《鴻蒙應用開發從入門到項目實戰》系列文章持續更新中,陸續更新AI+編程、企業級項目實戰等原創內容,防止迷路,歡迎關注!
作者:黑馬騰云
微信公眾賬號:自學幫
博客園:黑馬騰云博客
如果你想及時得到個人撰寫文章以及著作的消息推送,或者想看看個人推薦的技術資料,可以掃描左邊二維碼(或者長按識別二維碼)關注微信公眾號)。
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。
浙公網安備 33010602011771號