鸿蒙-数字键盘

首先声明数字键盘并定义其样式,使用 keyBoxStyle 将键盘样式抽取出来,之后直接调用即可:

numbers:string[]=['0','1','2','3','4','5','6','7','8','9','.']//定义键盘

  @Styles keyBoxStyle(){
    .backgroundColor(Color.White)
    .borderRadius(8)
    .height(60)
  }

  build() {
    Grid(){
      ForEach(this.numbers,num =>{
        GridItem(){
          Text(num).fontSize(20).fontWeight(CommonConstants.FONT_WEIGHT_900)
        }
        .keyBoxStyle()
      })
      GridItem(){
        Text('删除').fontSize(20).fontWeight(CommonConstants.FONT_WEIGHT_900)
      }
      .keyBoxStyle()
    }
    .width('100%')
    .height(300)
    .backgroundColor($r('app.color.index_page_background'))
    .columnsTemplate('1fr 1fr 1fr')
    .columnsGap(8)
    .rowsGap(8)//行间距
    .padding(8)
  }

实现效果:

接下来是键盘点击时间,包括输入的判断、数值的转换、删除事件等等,具体在代码注释中展示:

clickNumber(num:string){//点击数值
    //1.拼接用户输入的内容
    let val = this.value + num
    //2.校验输入格式
    let firstIndex=val.indexOf('.')//从第一个开始数小数点位置
    let lastIndex=val.lastIndexOf('.')//从后往前数
    if (firstIndex !== lastIndex || (lastIndex)!= -1 && lastIndex <val.length -2) {
      //有两个小数点或者小数点位数超过两位
      //非法输入
      return
    }
    //3.将字符串转为数值
    let amount = this.parseFloat(val)//格式化
    //4.保存
    if (amount >= 999.9) {//确保不会超出上限
      this.amount=999.0
      this.value='999'
    }else {
      this.amount=amount
      this.value=val
    }
  }

  clickDelete(){
    if (this.value.length <= 0) {
      this.value=''
      this.amount=0
      return
    }
    this.value=this.value.substring(0,this.value.length-1)
    this.amount=this.parseFloat(this.value)
  }

  parseFloat(str:string){
    if(!str){//删除到最后
      return 0
    }
    if (str.endsWith('.')) {
      str=str.substring(0,str.length-1)
    }
    return parseFloat(str)
  }

还有最终的按钮点击事件:

 //3.4按钮
          Row({space:CommonConstants.SPACE_6}){
            Button('取消')
              .width(120)
              .backgroundColor($r('app.color.light_gray'))
              .type(ButtonType.Normal)
              .borderRadius(6)
              .onClick(()=>this.showPanel=false)
            Button('提交')
              .width(120)
              .backgroundColor($r('app.color.primary_color'))
              .type(ButtonType.Normal)
              .borderRadius(6)
              .onClick(()=>this.showPanel=false)
          }
          .margin({top:10})

实现效果:

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值