應用中經常用到彈窗,比如警告彈窗、日期選擇彈窗、文本選擇彈窗以及其他自定義彈窗等等。本例將為大家介紹如何使用不同的彈窗。
效果呈現
本例最終效果如下:
示例中共涉及四類彈窗:
警告彈窗:提示信息尚未保存。
日期滑動選擇器彈窗:選擇出生日期。
文本滑動選擇器彈窗:選擇性別。
自定義彈窗:填寫興趣愛好。
說明:自定義彈窗可以根據業務需要自行定義彈窗的形式和內容,比如文本輸入、單選、多選等等,本例以文本輸入為例進行介紹。
運行環境
本例基于以下環境開發,開發者也可以基于其他適配的版本進行開發:
IDE:DevEco Studio 3.1 Release
SDK:Ohos_sdk_public 3.2.12.5(API Version 9 Release)
實現思路
本例中涉及的 4 類彈窗及實現方案如下:
警告彈窗:使用 AlertDialog 實現。
日期滑動選擇器彈窗:使用 DatePickerDialog 實現。
文本滑動選擇器彈窗:使用 TextPickerDialog 實現。
自定義彈窗:使用 CustomDialogController 實現。
開發步驟
由于本例重點講解對話框的使用,所以開發步驟會著重講解相關實現,不相關的內容不做介紹,全量代碼可參考完整代碼章節。
①首先,使用 AlertDialog 實現警告彈窗
通過 message 參數設置告警信息,alignment 設置彈窗在界面中垂直方向的對齊方式;通過 primaryButton 和 secondaryButton 添加按鈕。
具體代碼如下:
alertDialog(context:Context.UIAbilityContext){ AlertDialog.show({ //通過message設置告警信息 message:'當前數據未保存,是否確認離開?', //通過alignment設置彈窗在界面垂直方向的對齊方式,此處設置為底部對齊 alignment:DialogAlignment.Bottom, //通過offset設置基于對齊位置的便宜量 offset:{ dx:0, dy:-20 }, //彈窗中左起第一個按鈕 primaryButton:{ value:'取消', action:()=>{ console.info('Callbackcancelbuttonisclicked'); } }, //彈窗中左起第二個按鈕 secondaryButton:{ value:'確定', action:()=>{ //Exitingtheapp. context.terminateSelf(); console.info('Callbackdefinitebuttonisclicked'); } } }); }②使用 DatePickerDialog 實現日期滑動選擇器彈窗
通過 start 和 end 分別設置日期區間的起始時間和末尾時間;通過 lunar 設置使用農歷還是陽歷;使用 onAccept 監聽選擇的日期,本例中通過變量 selectedDate 將選中的日期設置給參數 selected,這樣彈窗彈出時的日期就默認為上次選中的日期。
具體代碼如下:
datePickerDialog(dateCallback){ DatePickerDialog.show({ start:newDate('1900-1-1'), end:newDate('2100-1-1'), //通過變量selectedDate將選中的日期設置給參數selected selected:this.selectedDate, lunar:false, //使用onAccept監聽選擇的日期 onAccept:(value:DatePickerResult)=>{ letyear=value.year; letmonth=value.month+1; letday=value.day; letbirthdate:string=this.getBirthDateValue(year,month,day); //通過setFullYear將選中的日期傳遞給變量selectedDate this.selectedDate.setFullYear(value.year,value.month,value.day) //返回選中的日期 dateCallback(birthdate); } }); }③使用 TextPickerDialog 實現文本滑動選擇器彈窗
通過 range 設置文本選擇項,使用 onAccept 監聽選擇的文本項,本例中通過變量 selectedGender 將選中的性別的索引設置給參數 selected,這樣彈窗彈出時的性別就默認為上次選中的性別。
具體代碼如下:
textPickerDialog(sexArray:Resource,sexCallback){ //判斷文本項的列表是否為空 if(this.isEmptyArr(sexArray)){ console.error('sexisnull'); return; } TextPickerDialog.show({ //通過range設置文本選擇項 range:sexArray, //通過變量selectedGender將選中的性別的索引設置給參數selected selected:this.selectedGender, //使用onAccept監聽選擇的文本項 onAccept:(result:TextPickerResult)=>{ sexCallback(result.value); //獲取選中項的索引 this.selectedGender=result.index }, onCancel:()=>{ console.info('TextPickerDialogonCancel'); } }); }
④使用 CustomDialogController 實現自定義彈窗
當現有彈窗不能滿足業務訴求時,開發者可以自行設計彈窗的樣式。在實現自定義彈窗時,需要將彈窗的 UI 放在被 @CustomDialog 修飾的自定義組件中,然后使用 CustomDialogController 的實例來控制彈窗的彈出和關閉。
具體代碼如下:
//使用@CustomDialog修飾自定義彈窗 @CustomDialog structCustomDialogFrame{ ... //定義CustomDialogController controller:CustomDialogController build(){ Column(){ Text('興趣愛好').fontSize(20).margin({top:10,bottom:10}) TextInput({placeholder:'',text:this.textValue}).height(60).width('90%') .onChange((value:string)=>{ this.textValue=value }) Flex({justifyContent:FlexAlign.SpaceAround}){ Button('取消') .onClick(()=>{ //點擊‘取消’,彈窗關閉 this.controller.close() }) .backgroundColor('') .fontColor('#007DFF') Button('保存') .onClick(()=>{ this.inputValue=this.textValue //點擊‘保存’,彈窗關閉 this.controller.close() }) .backgroundColor(0xffffff) .fontColor('#007DFF') }.margin({bottom:10}) }.justifyContent(FlexAlign.Start) } } ... //實例化自定義彈窗 customDialogController:CustomDialogController=newCustomDialogController({ //使用上文創建的自定義彈窗進行實例化 builder:CustomDialogFrame({ textValue:$textValue, inputValue:$inputValue }), alignment:DialogAlignment.Bottom, offset:{ dx:0, dy:-20 } }); ...
完整代碼
本例完整代碼如下:
importContextfrom'@ohos.app.ability.common'; importhilogfrom'@ohos.hilog'; @Component structTextFrame{ @Linkcontent:string; privatetextImage:Resource; privatetext:string; onTextClick:()=>void; build(){ Row(){ Image(this.textImage) .width(24) .height(24) .margin({left:12}) Text(this.text) .fontSize(16) .margin({left:12}) .height(24) Text(this.content) .fontSize(16) .textAlign(TextAlign.End) .textOverflow({overflow:TextOverflow.Ellipsis}) .maxLines(1) .margin({ left:16, right:7 }) .layoutWeight(1) .width('100%') Image($r('app.media.ic_arrow')) .width(12) .height(24) .margin({right:14}) } .margin({top:24}) .borderRadius(24) .backgroundColor(Color.White) .width('93.3%') .height(64) .onClick(this.onTextClick) } } @Component structInputFrame{ privateinputImage:Resource; privatehintText:string; build(){ Row(){ Image(this.inputImage) .width(24) .height(24) .margin({left:12}) TextInput({placeholder:this.hintText}) .fontSize(16) .padding({left:12}) .placeholderColor('#99000000') .backgroundColor(Color.White) .fontWeight(FontWeight.Normal) .fontStyle(FontStyle.Normal) .fontColor(Color.Black) .margin({right:32}) .layoutWeight(1) .height(48) } .margin({top:24}) .borderRadius(24) .backgroundColor(Color.White) .width('93.3%') .height(64) } } @CustomDialog structCustomDialogFrame{ @LinktextValue:string @LinkinputValue:string controller:CustomDialogController build(){ Column(){ Text('興趣愛好').fontSize(20).margin({top:10,bottom:10}) TextInput({placeholder:'',text:this.textValue}).height(60).width('90%') .onChange((value:string)=>{ this.textValue=value }) Flex({justifyContent:FlexAlign.SpaceAround}){ Button('取消') .onClick(()=>{ this.controller.close() }).backgroundColor('').fontColor('#007DFF') Button('保存') .onClick(()=>{ this.inputValue=this.textValue this.controller.close() }).backgroundColor(0xffffff).fontColor('#007DFF') }.margin({bottom:10}) }.justifyContent(FlexAlign.Start) } } @Entry @Component structIndex{ @Statebirthdate:string=''; @Statesex:string=''; @StatetextValue:string=''; @StateinputValue:string=''; selectedDate:Date=newDate("2010-1-1") selectedGender:number=0 privatesexArray:Resource=$r('app.strarray.sex_array'); customDialogController:CustomDialogController=newCustomDialogController({ builder:CustomDialogFrame({ textValue:$textValue, inputValue:$inputValue }), alignment:DialogAlignment.Bottom, offset:{ dx:0, dy:-20 } }); alertDialog(context:Context.UIAbilityContext){ AlertDialog.show({ message:'當前數據未保存,是否確認離開?', alignment:DialogAlignment.Bottom, offset:{ dx:0, dy:-20 }, primaryButton:{ value:'取消', action:()=>{ console.info('Callbackcancelbuttonisclicked'); } }, secondaryButton:{ value:'確定', action:()=>{ //Exitingtheapp. context.terminateSelf(); console.info('Callbackdefinitebuttonisclicked'); } } }); } datePickerDialog(dateCallback){ DatePickerDialog.show({ start:newDate('1900-1-1'), end:newDate('2100-1-1'), selected:this.selectedDate, lunar:false, onAccept:(value:DatePickerResult)=>{ letyear=value.year; letmonth=value.month+1; letday=value.day; letbirthdate:string=this.getBirthDateValue(year,month,day); this.selectedDate.setFullYear(value.year,value.month,value.day) dateCallback(birthdate); } }); } textPickerDialog(sexArray:Resource,sexCallback){ if(this.isEmptyArr(sexArray)){ console.error('sexisnull'); return; } TextPickerDialog.show({ range:sexArray, selected:this.selectedGender, onAccept:(result:TextPickerResult)=>{ sexCallback(result.value); this.selectedGender=result.index }, onCancel:()=>{ console.info('TextPickerDialogonCancel'); } }); } getBirthDateValue(year:number,month:number,day:number):string{ letbirthdate:string=`${year}${'年'}${month}`+ `${'月'}${day}${'日'}`; returnbirthdate; } isEmpty(obj):boolean{ returnobj===undefined||obj===null||obj===''; } isEmptyArr(array):boolean{ returnthis.isEmpty(array)||array.length===0; } build(){ Row(){ Column(){ Row(){ Image($r('app.media.ic_back')) .width(26) .height(26) .alignSelf(ItemAlign.Start) .margin({ left:'7.2%', top:19 }) .onClick(()=>{ letcontext=getContext(this)asContext.UIAbilityContext; this.alertDialog(context); }) Text('個人信息') .fontColor(Color.Black) .fontSize(20) .margin({top:20,left:20}) .alignSelf(ItemAlign.Center) }.width('100%') Image($r('app.media.ic_avatar')) .width(56) .height(56) .alignSelf(ItemAlign.Center) .margin({top:'5.5%'}) Text('頭像') .fontColor(Color.Black) .fontSize(16) .margin({top:'2.1%'}) .alignSelf(ItemAlign.Center) InputFrame({ inputImage:$r('app.media.ic_nickname'), hintText:'昵稱' }) TextFrame({ textImage:$r('app.media.ic_birthdate'), text:'出生日期', content:$birthdate, onTextClick:()=>{ this.datePickerDialog((birthValue:string)=>{ this.birthdate=birthValue; }); } }) TextFrame({ textImage:$r('app.media.ic_sex'), text:'性別', content:$sex, onTextClick:()=>{ this.textPickerDialog(this.sexArray,(sexValue:string)=>{ this.sex=sexValue; }); } }) InputFrame({ inputImage:$r('app.media.ic_signature'), hintText:'個性簽名' }) TextFrame({ textImage:$r('app.media.ic_hobbies'), text:'興趣愛好', content:$textValue, onTextClick:()=>{ this.customDialogController.open(); } }) } .backgroundColor('#F5F5F5') .height('100%') .width('100%') } .height('100%') } }
審核編輯:劉清
-
OpenHarmony
+關注
關注
25文章
3753瀏覽量
16698
原文標題:OpenHarmony上使用彈窗
文章出處:【微信號:gh_834c4b3d87fe,微信公眾號:OpenHarmony技術社區】歡迎添加關注!文章轉載請注明出處。
發布評論請先 登錄
相關推薦
鴻蒙原生開源庫ViewPool在OpenHarmony社區正式上線
OpenHarmony人才生態大會南向生態社區發展論壇在武漢圓滿舉辦
![<b class='flag-5'>OpenHarmony</b>人才生態大會南向生態社區發展論壇<b class='flag-5'>在</b>武漢圓滿舉辦](https://file1.elecfans.com//web3/M00/00/66/wKgZO2dJIDCAD9paAAEFSUV2MvU065.png)
OpenHarmony人才生態大會南向生態社區發展論壇在武漢圓滿舉辦
基于ArkTS語言的OpenHarmony APP應用開發:HelloOpenharmony
![基于ArkTS語言的<b class='flag-5'>OpenHarmony</b> APP應用開發:Hello<b class='flag-5'>Openharmony</b>](https://file.elecfans.com/web2/M00/26/21/pYYBAGG5jjSALfrEAAAwAa9Oig8799.png)
第二屆大會回顧第25期 | OpenHarmony上的Python設備應用開發
![第二屆大會回顧第25期 | <b class='flag-5'>OpenHarmony</b><b class='flag-5'>上</b>的Python設備應用開發](https://file1.elecfans.com/web2/M00/04/4E/wKgZombNTbKAGXSVAAARd6jESHY243.jpg)
HarmonyOS實戰開發-全局彈窗封裝案例
HarmonyOS實戰開發-如何使用全局狀態保留能力彈窗來實現評論組件。
HarmonyOS實戰開發-全局狀態保留能力彈窗
OpenHarmony內核編程實戰
![<b class='flag-5'>OpenHarmony</b>內核編程實戰](https://file1.elecfans.com/web2/M00/8F/50/wKgZomTMciWAD54NAABOGP2pQZY452.png)
介紹一種OpenAtom OpenHarmony輕量系統適配方案
![介紹一種OpenAtom <b class='flag-5'>OpenHarmony</b>輕量系統適配方案](https://file1.elecfans.com/web2/M00/C3/89/wKgaomXmdQ2API-MAAAONfnizq8510.png)
評論