在OpenHarmony上如何使用不同的弹窗

应用中经常用到弹窗,比如警告弹窗、日期选择弹窗、文本选择弹窗以及其他自定义弹窗等等。本例将为大家介绍如何使用不同的弹窗。
效果呈现
本例最终效果如下:
示例中共涉及四类弹窗:
警告弹窗:提示信息尚未保存。
日期滑动选择器弹窗:选择出生日期。
文本滑动选择器弹窗:选择性别。
自定义弹窗:填写兴趣爱好。
说明:自定义弹窗可以根据业务需要自行定义弹窗的形式和内容,比如文本输入、单选、多选等等,本例以文本输入为例进行介绍。
运行环境
本例基于以下环境开发,开发者也可以基于其他适配的版本进行开发:
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('callback cancel button is clicked');      }    },    // 弹窗中左起第二个按钮    secondarybutton: {      value: '确定',      action: () => {        // exiting the app.        context.terminateself();        console.info('callback definite button is clicked');      }    }  });}②使用 datepickerdialog 实现日期滑动选择器弹窗
通过 start 和 end 分别设置日期区间的起始时间和末尾时间;通过 lunar 设置使用农历还是阳历;使用 onaccept 监听选择的日期,本例中通过变量 selecteddate 将选中的日期设置给参数 selected,这样弹窗弹出时的日期就默认为上次选中的日期。 具体代码如下:
datepickerdialog(datecallback) {  datepickerdialog.show({    start: new date('1900-1-1'),    end: new date('2100-1-1'),    // 通过变量selecteddate将选中的日期设置给参数selected    selected: this.selecteddate,    lunar: false,    // 使用onaccept监听选择的日期    onaccept: (value: datepickerresult) => {      let year = value.year;      let month = value.month + 1;      let day = value.day;      let birthdate: 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('sex is null');    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('textpickerdialog oncancel');    }  });} ④使用 customdialogcontroller 实现自定义弹窗
当现有弹窗不能满足业务诉求时,开发者可以自行设计弹窗的样式。在实现自定义弹窗时,需要将弹窗的 ui 放在被 @customdialog 修饰的自定义组件中,然后使用 customdialogcontroller 的实例来控制弹窗的弹出和关闭。
具体代码如下:
// 使用@customdialog修饰自定义弹窗@customdialogstruct customdialogframe{  ...  // 定义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 = new customdialogcontroller({    // 使用上文创建的自定义弹窗进行实例化    builder: customdialogframe({      textvalue: $textvalue,      inputvalue: $inputvalue    }),    alignment: dialogalignment.bottom,    offset: {      dx: 0,      dy: -20    }  });...
完整代码
本例完整代码如下:
import context from '@ohos.app.ability.common';import hilog from '@ohos.hilog';@componentstruct textframe{  @link content: string;  private textimage:resource;  private text: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)  }}@componentstruct inputframe{  private inputimage: resource;  private hinttext: 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)  }}@customdialogstruct customdialogframe{  @link textvalue: string  @link inputvalue: 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@componentstruct index {  @state birthdate: string = '';  @state sex: string = '';  @state textvalue: string = '';  @state inputvalue: string = '';  selecteddate: date = new date(2010-1-1)  selectedgender:number = 0  private sexarray: resource = $r('app.strarray.sex_array');  customdialogcontroller: customdialogcontroller = new customdialogcontroller({    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('callback cancel button is clicked');        }      },      secondarybutton: {        value: '确定',        action: () => {          // exiting the app.          context.terminateself();          console.info('callback definite button is clicked');        }      }    });  }  datepickerdialog(datecallback) {    datepickerdialog.show({      start: new date('1900-1-1'),      end: new date('2100-1-1'),      selected: this.selecteddate,      lunar: false,      onaccept: (value: datepickerresult) => {        let year = value.year;        let month = value.month + 1;        let day = value.day;        let birthdate: 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('sex is null');      return;    }    textpickerdialog.show({      range: sexarray,      selected: this.selectedgender,      onaccept: (result: textpickerresult) => {        sexcallback(result.value);        this.selectedgender = result.index      },      oncancel: () => {        console.info('textpickerdialog oncancel');      }    });  }  getbirthdatevalue(year: number, month: number, day: number): string {    let birthdate: string = `${year}${'年'}${month}` +    `${'月'}${day}${'日'}`;    return birthdate;  }  isempty(obj): boolean {    return obj === undefined || obj === null || obj === '';  }  isemptyarr(array): boolean {    return this.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(() => {              let context = getcontext(this) as context.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%')  }}


TD-SCDMA/GSM无线通讯模块TM600A
三星和苹果在全球智能手机市场的份额正越来越多地被华为蚕食
如何改善CAN电磁兼容性的措施
虚拟主机十大品牌_中国十大虚拟主机服务商排名
测量精准、功能全面的血压手表到底有哪些黑科技?
在OpenHarmony上如何使用不同的弹窗
骨传导耳机哪个牌子好、最佳骨传导耳机
智己:自动驾驶前的最后一战
QXXZ-270kVA/108kV 变频串联谐振试验装置谐振方案
干电池原理
人脸识别、自助收银等技术将给零售行业带来哪些益处
大棚智能控制系统对温室有什么用
人工智能已经发展到各个行业都有它的身影
iPhone 3GS常见问题咨询答疑大收集
球罐雷达液位计安装注意事项
京东方今年要给华为供应100万块自主柔性OLED屏
大华发布巨灵人工智能开发平台 赋能千行百业数智化升级
努比亚Z17mini、荣耀V9对比评测:谁才是其中翘楚?
iphone8什么时候上市?iphone8最新消息:库克表示今年iPhone卖的不好全是iPhone8惹的祸
显示屏制造商维信诺或推出自家的折叠屏智能机